.net - 如何设置 StructureMap 来解决 Windows 服务中的依赖关系?

标签 .net windows-services inversion-of-control structuremap

我有一个使用 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/

相关文章:

windows-services - 将 Selenium RC 作为 Windows 服务运行

c# - 设置并发作业的最大值 Quartz.Net

inversion-of-control - 如果您使用控制反转,构造函数的大小是否重要?

PHP-DI injectOn 不注入(inject) setter 方法

c# - WCF契约不匹配问题

.net - 修复此生成空字符串的排列生成器函数

windows - Log4Net 与 WCF 作为服务运行

inversion-of-control - CaSTLe Windsor 如何响应实现多个接口(interface)的类?

c# - 如何让AutoFixture从多个TypeRelay中随机选择?

c# - 以 WebBrowser 窗体(Windows 窗体 C#)完全加载页面时的 DocumentCompleted 事件