如何在 StructureMap ServiceActivator 中使用 Container 而不是 ObjectFactory? [英] How to use Container instead of ObjectFactory in StructureMap ServiceActivator?
问题描述
在使用 StructureMap 在 WebAPI 中实现 DI 时,我们使用了
When implementing DI in WebAPI with StructureMap, we used the ServiceActivator found in
public class ServiceActivator : IHttpControllerActivator
{
public ServiceActivator(HttpConfiguration configuration) {}
public IHttpController Create(HttpRequestMessage request,
HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = ObjectFactory.GetInstance(controllerType) as IHttpController;
return controller;
}
}
但是现在有了新的 StructureMap,我的 ReSharper 建议:
But now with the new StructureMap, my ReSharper suggested:
StructureMap.ObjectFactory"类已过时:ObjectFactory 将在 StructureMap 的未来 4.0 版本中删除.支持使用 Container 类以备将来工作
Class 'StructureMap.ObjectFactory' is obsolete: ObjectFactory will be removed in a future 4.0 release of StructureMap. Favor the usage of the Container class for future work
Container
上的智能感知只给了我非常有限的信息.
The intellisense on Container
gave me only very limited information.
我们应该如何使用 Container 类重写我们的 ServiceActivator?
How are we supposed to rewrite our ServiceActivator with the Container class?
推荐答案
静态内容正在发生离开.如果您不使用某种类型的服务定位器,您将实现自己的ObjectFactory
"作为 此处引用:
The static stuff is going away. If your not using a Service Locator of some type you're going to have implement your own "ObjectFactory
" as referenced here:
public static class ObjectFactory
{
private static readonly Lazy<Container> _containerBuilder =
new Lazy<Container>(defaultContainer, LazyThreadSafetyMode.ExecutionAndPublication);
public static IContainer Container
{
get { return _containerBuilder.Value; }
}
private static Container defaultContainer()
{
return new Container(x =>
{
// default config
});
}
}
更新:我之前的回答是错误的.感谢@JoeMighty 的提醒.
Update: My previous answer was wrong. Thanks @JoeMighty for the heads up.
这篇关于如何在 StructureMap ServiceActivator 中使用 Container 而不是 ObjectFactory?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!