问题
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