Unity懒惰决心
问题描述:
我有MVC
webApi
应用程序与Unity
一起使用。我必须将接口ITest
解析为单例类(DelegateHandler
)。但是ITest拥有每个httprequest
终生管理者,这很重要。所以我不能在Application_Start
事件上解决ITest问题,因为现在没有HttpRequest,但DelegateHandler只会在httprequest生命周期中使用ITest。Unity懒惰决心
那么是否有可能将懒惰的决心发送给DelegateHandler,或者也许有人有其他有趣的解决方案?
答
服务的生命周期应该永远比它的依赖等于或短,所以你通常会注册ITest
为每HTTP请求或短暂的,但如果这是不可能的,包的依赖(DelegateHandler
我假设)有在代理每一个HTTP请求的生命周期:
// Proxy
public class DelegateHandlerProxy : IDelegateHandler
{
public Container Container { get; set; }
// IDelegateHandler implementation
void IDelegateHandler.Handle()
{
// Forward to the real thing by resolving it on each call.
this.Container.Resolve<RealDelegateHandler>().Handle();
}
}
// Registration
container.Register<IDelegateHandler>(new InjectionFactory(
c => new DelegateHandlerProxy { Container = c }));
答
另一种方法是做到以下几点:
public class Foo
{
Func<IEnumerable<ITest>> _resolutionFunc;
ITest _test;
public Foo(Func<IEnumerable<ITest>> resolutionFunc)
{
_resolutionFunc=resolutionFunc;
}
private void ResolveFuncToInstance()
{
_test=_resolutionFunc().First();
}
}
我们正在做的是要求统一向我们提供的委托,将解决所有ITEST instan ces在容器里。由于这是一个Func,我们可以在我们想要从Unity中做出实际分辨率时调用它。
这确实很多同样的事情,史蒂芬是干什么的,但使用内置统一的功能做什么,我们要寻找的。
谢谢,非常好的答案! – 2012-04-05 10:59:35
将它转换成通用的解决方案很酷,但可以propably这是不可能的) – 2012-04-06 07:51:21