【发布时间】:2010-11-13 21:21:19
【问题描述】:
我正在尝试开始使用 Unity,但我有一点把握。
我有一个 Context 类和一个由容器解析的 Repository 类。 我的 Repository 类将 Context ctor 参数作为依赖项。
我的配置文件:
容器:
<register type="IGeneralContext" mapTo="Data.EF.EFContext, Data.EF">
<lifetime type="singleton" />
<constructor>
<param name="connectionString">
<value value="anyConnStr"/>
</param>
</constructor>
</register>
<register type="IClienteRepository" mapTo="Repository.EF.ClientRepository, Repository.EF">
<constructor>
<param name="context">
<dependency type="Data.EF.EFContext, Data.EF"/>
</param>
</constructor>
</register>
现在,我希望在调用 Resolve 并且旧的实例已经发布时构建 IGeneralContext 的新实例。
见:
using (IGeneralContext context = container.Resolve<IGeneralContext>()) //NEW CONTEXT INSTANCE
{
IClienteRepository rep = container.Resolve<IClienteRepository>(); // USE DEPENDENCY AS SINGLETON
Cliente nc = new Cliente() { };
rep.Add(nc);
context.CommitChanges();
} // DISPOSE CONTEXT
using (IGeneralContext context = container.Resolve<IGeneralContext>()) //BRAND NEW CONTEXT INSTANCE
{
IClienteRepository rep = container.Resolve<IClienteRepository>(); // USE DEPENDENCY AS SINGLETON
Cliente nc = new Cliente() { };
rep.Add(nc);
context.CommitChanges();
} // DISPOSE CONTEXT
IClienteRepository rep1 = container.Resolve<IClienteRepository>(); // NEW CONTEXT AGAIN
Cliente cliente1= rep1.GetById(1);
知道如何使用 Unity 解决它吗?
谢谢。
【问题讨论】:
标签: dependency-injection unity-container ioc-container