DependencyResolver: Pass parameters

允我心安 提交于 2020-02-07 07:50:11

问题


I use autofac and can pass parameters to my resolve method.

How can I do this using microsofts DependencyResolver interface?


回答1:


The IDependencyResolver does not support passing parameters directly, as I'm sure you have noticed. However, since you have Autofac under the hood, you're able to resolve a factory delegate that enables you to pass on parameters to the underlying service:

var factory = dependencyResolver.GetService<Func<int, string, IService>>();
var service = factory(5, "42");

Note: you can either use Func delegates or explicitly defined factory delegates. More on this here.

Regarding lifetime scopes: factory delegates must be resolved from a scope where the requested service can be "reached". Consider this setup simulating how MVC or WebApi would look like:

var cb = new ContainerBuilder();
cb.RegisterType<X>().InstancePerMatchingLifetimeScope("http");
var application = cb.Build();
var request = application.BeginLifetimeScope("http");

With this setup, our X service will only be available in the http scope. Trying to resolve X from application scope will fail with this message:

No scope with a Tag matching 'http' is visible from the scope in which the instance was requested.

Resolving from the request scope will work as expected:

var f = request.Resolve<Func<IX>>();
var x = f();



回答2:


The general advice is to resolve a factory. Either you define a custom factory interface for the type you need to resolve (this has my preference), or resolve a delegate (which is what Peter Lillevold suggests). Either way, you should not call the container (or DependencyResolver for that matter) directly, since this is sub optimal.



来源:https://stackoverflow.com/questions/11901642/dependencyresolver-pass-parameters

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