问题描述
我用autofac,可以传递参数给我的决心的方法。
I use autofac and can pass parameters to my resolve method.
我怎样才能做到这一点使用微软DependencyResolver接口?
How can I do this using microsofts DependencyResolver interface?
推荐答案
的不支持直接传递参数,因为我相信你已经注意到了。不过,既然你有Autofac引擎盖下,你能解决工厂的委托,使您能够在参数传递到底层服务:
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.
对于生命周期范围:工厂代表必须从范围来解决所请求的服务可以达到了。考虑这个设置模拟MVC和的WebAPI怎么会是这样的:
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");
通过这种设置,我们的 X
服务将只能在HTTP范围内使用。试图解决 X
从应用
范围将失败,此消息:
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:
没有一个标签匹配'HTTP'范围从可见光范围
其中要求该实例。
从要求
范围将作为解决预期的:
Resolving from the request
scope will work as expected:
var f = request.Resolve<Func<IX>>();
var x = f();
这篇关于DependencyResolver:传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!