当
FirstContext
和
PaymentsContext
让每个实体都有一组唯一的实体(例如,每个实体都连接到不同的数据库),在代码中显式地定义它是值得的。一种方法是为每个工作单元指定一个工厂:
public interface IFirstContextFactory
{
IUnitOfWork CreateNew();
}
public interface IPaymentContextFactory
{
IUnitOfWork CreateNew();
}
public class PaymentController()
{
public PaymentController(PaymentContextFactory paymentContextFactory)
{
//How to I tell unity that this needs to be a payments
this.paymentContextFactory = paymentContextFactory;
}
public void DoSomething()
{
using (var context = this.paymentContextFactory.CreateNew())
{
// Do something useful
context.Commit();
}
}
}
这不仅使您的依赖关系非常清楚(因为您知道代码处理的是什么类型的上下文),而且还简化了DI配置,因为您不需要任何命名注册。