我有一个使用 ASP.NET MVC 1.0 构建的网站。它使用 Structuremap 作为 IOC 容器。 如果我像这样在 Application_Start 上注册 IOC 部分,它会很好用:
ObjectFactory.Initialize(service =>
{
service.ForRequestedType<IOrderRepository>()
.TheDefaultIsConcreteType<OrderRepository>()
.CacheBy(InstanceScope.PerRequest);
});
我必须在 Windows 服务中使用相同的后端。
服务中有一些计时器可以同时访问 OrderRepository,因此这里线程是一个问题。
我的第一个想法是像这样在服务的构造函数中注册它:
public Service1()
{
ObjectFactory.Initialize(service =>
{
service.ForRequestedType<IOrderRepository>()
.TheDefaultIsConcreteType<OrderRepository>()
.CacheBy(InstanceScope.PerRequest);
});
}
这是缓存的正确位置和正确参数吗?
阅读documentation of Structuremap ,我认为最安全的方法是使用缓存的默认设置:
PerRequest - The default operation. A new instance will be created for each request.
我的印象是 PerRequest 意味着 HttpContext,但那是另一个条目:
HttpContext - A single instance will be created for each HttpContext. Caches the instances in the
HttpContext.Items
collection.
最佳答案
根据这篇文章:http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.aspx
The executable calls the ServiceBase derived class's constructor the first time you call Start on the service. The OnStart command-handling method is called immediately after the constructor executes. The constructor is not executed again after the first time the service has been loaded, so it is necessary to separate the processing performed by the constructor from that performed by OnStart. Any resources that can be released by OnStop should be created in OnStart. Creating resources in the constructor prevents them from being created properly if the service is started again after OnStop has released the resources.
听起来构造函数是第一次设置结构图的方法。
关于.net - 如何设置 StructureMap 来解决 Windows 服务中的依赖关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7915323/