0

在我的应用程序中引入消息传递后,似乎我发现了一点气味。IoC /依赖注入 - 如何处理上下文依赖关系(使用Structuremap)

在我的多租户应用程序中,文件系统被抽象并限定为每个租户。因此,如果一个服务需要创建文件,那么我们注入一个IFileSystem的实例,该实例将被限定在租户目录/容器中。

这是通过配置结构图来获取具有当前用户站点的上下文对象来构建IFileSystem实现来实现的。

现在我们需要在没有上下文并且没有当前用户的情况下(在后台线程上)使用文件系统。这里有一个简单的例子:

public class SiteContext 
    { 
     public string SiteId { get { return "Site123"; } } 
    } 

    public class FileSystemSettings 
    { 
     public string BaseDirectory { get; set; } 
    } 

    public interface IFileSystem { } 

    public class DefaultFileSystem : IFileSystem 
    { 
     public DefaultFileSystem(FileSystemSettings settings) 
     { 

     } 
    } 

    public interface ISomeService { } 

    public class SomeService : ISomeService 
    { 
     public SomeService(IFileSystem fileSystem) 
     { 

     } 
    } 

    public class TestMessageHandler : IMessageHandler<TestMessage> 
    { 
     public TestMessageHandler(ISomeService someService) 
     { 
      // oO we don't have access to site context here :(
     } 
    } 

我想我可以改变我的文件系统实现,露出FileSystemSettings的属性,因此它可以事后集。

然而,即使这样仍然需要我手动构建我ISomeService对象,这是一种痛苦,因为一些我的服务有许多依赖=很多电话到ObjectFactory.GetInstance...

想法?

+0

http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#1945023 –

+0

你能澄清这个问题吗?你打算如何使用SiteContext?显示正在工作的代码,并指出不是的代码。 –

回答

1

你可能use nested containers并配置嵌套容器有一个虚拟实现你的上下文。

的代码将大约是:

using (var container = ObjectFactory.Container.GetNestedContainer()) 
{ 
    container.Configure(config => { 
     config.For<ISiteContext>().Use<DummyContext>(); 
    }); 

    return container.GetInstance<TestMessageHandler>(); 
} 

这应该设置自定义(虚拟)执行ISiteContext不会覆盖全球集装箱(ObjectFactory.Container)。当然,如果没有更多信息,我不能给你一个合适的DummyContext实施。但是这应该让你开始。