[英]How should I handle my Entity/Domain Objects using IoC/Dependency Injection?
[英]IoC / Dependency Injection - How to handle contextual dependencies (using Structuremap)
在我的应用程序中引入消息传递之后,我似乎发现了一点异味。
在我的多租户应用程序中,文件系统是针对每个租户进行抽象和限定的。 因此,如果服务需要创建文件,那么我们会注入一个 IFileSystem 实例,该实例将作用于租户目录/容器。
这是通过配置结构映射来构建 IFileSystem 实现的,方法是获取具有当前用户站点的上下文 object。
现在我们需要在没有上下文且没有当前用户(在后台线程上)时使用文件系统。 这是一个简单的例子:
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 :(
}
}
我想我可以更改我的 FileSystem 实现以将FileSystemSettings
公开为属性,以便以后可以设置它。
但是,即使这样做仍然需要我手动构建我的 ISomeService object,这很痛苦,因为我的一些服务有许多依赖项 = 对ObjectFactory.GetInstance...
想法?
您可以使用嵌套容器并将嵌套容器配置为具有您的上下文的虚拟实现。
代码大约是:
using (var container = ObjectFactory.Container.GetNestedContainer())
{
container.Configure(config => {
config.For<ISiteContext>().Use<DummyContext>();
});
return container.GetInstance<TestMessageHandler>();
}
这应该设置ISiteContext
的自定义(虚拟)实现而不覆盖全局容器( ObjectFactory.Container
)。 当然,如果没有更多信息,我无法为您提供DummyContext
的适当实现。 但这应该让你开始。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.