https://stackoverflow.com/questions/24188025/is-there-another-way-of-changing-database-instance-in-autofac
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);
}
}
来源:oschina
链接:https://my.oschina.net/u/4329662/blog/3639551