autofac &web api 切换数据库

你。 提交于 2021-02-19 01:49:42

https://stackoverflow.com/questions/24188025/is-there-another-way-of-changing-database-instance-in-autofac

 

WebAPI: Retrieve GET parameter from Controller Constructor

The constructor is invoked too early, you can't access the parameters from there. However, you can override the Initialize method and retrieve the GET parameters from the context:

protected override void Initialize(HttpControllerContext controllerContext) { foreach (var parameter in controllerContext.Request.GetQueryNameValuePairs()) { Debug.WriteLine(string.Format("{0} = {1}", parameter.Key, parameter.Value)); } base.Initialize(controllerContext); }

可以通过下面的代码拿到post方法的RequestBody。   post的参数通过ActionFilter来处理会更好

string requestBody = await controllerContext.Request.Content.ReadAsStringAsync();

 

可以把c也作为参数传递过去,然后c可以对service进行resolve

builder.Register((c,p) => GetProgramContract(c,p.Named<MessageHeader>("Header"))).As<IProgramContract>().InstancePerLifetimeScope();
            builder.Register((c,p) => new DynamicProfileService(GetProgramContract(c,p.Named<MessageHeader>("Header")))).As<IDynamicProfileService>().InstancePerLifetimeScope();


 private static ProgramContract GetProgramContract(IComponentContext c, MessageHeader header)
        {
            var reportContract = c.Resolve<IReportContract>();
            var adminWebContract = c.Resolve<IAdminWebContract>();
            var serviceFactory = c.Resolve<IContractFactory>();

            var connectionString = adminWebContract.AdminWebGetRepositoryConnectionString();
            RepositoryComponent repositoryComponent = new RepositoryComponent(reportContract);
            var program = repositoryComponent.GetProgramIdAndCultureCodeByCountryCode(connectionString,header.OpCo);

            var programContract =
                new ProgramContract(serviceFactory, program.Id, program.CultureCode, program.CountryCode);
            return programContract;
        }

 

最新的方法2019-02-26

发现通过ActionFilter来处理,是最好的办法。通过actionContext可以得到controller,并且也可以得到已经解析好的actionContext.ActionArguments["request"]。通过dynamic直接调用后台已知的必定会存在的property。

将参数传递给autofac,autofac那边根据传递过来的参数不同,实例化不同的 数据库连接

public class ServiceInitializeAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            dynamic obj = actionContext.ActionArguments["request"];
            var controllerContext = actionContext.ControllerContext;
            var controller = controllerContext.Controller as BaseApiController;
            var dependencyScope = controllerContext.Request.GetDependencyScope();
            var lifetimeScope = dependencyScope.GetRequestLifetimeScope();
            if (controller == null)
            {
                throw new NotSupportedException($"Type {controllerContext.Controller.GetType()} is not supported.");
            }
            var parameter = new NamedParameter("Header", obj.Header);
            controller.Program = lifetimeScope.Resolve<IProgramContract>(parameter);
            controller.Service = lifetimeScope.Resolve<IDynamicProfileService>(parameter);
        }
    }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!