DependencyResolver:传递参数 [英] DependencyResolver: Pass parameters

查看:416
本文介绍了DependencyResolver:传递参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用autofac,可以传递参数给我的决心的方法。

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

我怎样才能做到这一点使用微软DependencyResolver接口?

How can I do this using microsofts DependencyResolver interface?

推荐答案

的IDependencyResolver 不支持直接传递参数,因为我相信你已经注意到了。不过,既然你有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'范围从可见光范围
      其中要求该实例。

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();

这篇关于DependencyResolver:传递参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆