为特定接口指定单独的注入

时间:2015-03-18 20:14:18

标签: c# structuremap

假设我有以下层次结构,我希望用DI实例化:

DatabaseService(IDatabaseRepository) : IDatabaseService
Database1Service(IDatabaseRepository) : IDatabase1Service
Database2Service(IDatabaseRepository) : IDatabase2Service
DatabaseRepository(IUnitOfWork)  : IDatabaseRepository
DatabaseRepository2(IUnitOfWork) : IDatabaseRepository
UnitOfWork(string) : IUnitOfWork

Stucturemap中是否有方法可以让我这样做?

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        //default-convention-scan code here

        //this is the unit of work for almost all of my interface implementations
        //i.e. new DatabaseService(new DatabaseRepository(new IUnitOfWork("Database1")))
        //    new Database1Service(new DatabaseRepository(new IUnitOfWork("Database1")))
         For<IUnitOfWork>()
             .Use(new UnitOfWork("Database1"));

         //Database2Service needs a separate implementation Of UnitOfWork
        //i.e. new Database2Service(new DatabaseRepository(new IUnitOfWork("Database2")))
         For<IUnitOfWork>().IfDescendantDependencyOf<IDatabase2Service>()
             .Use(new UnitOfWork("Database2"))
    }
}

如果不清楚,我希望所有注入的IUnitOfWork都指向单例new UnitOfWork("Database1"),除非它是在尝试构造IDatabase2Service的实例时注入的,它应该在使用单身new UnitOfWork("Database2")

1 个答案:

答案 0 :(得分:0)

这可以通过使用以下配置来实现:

public class MyRegistry : Registry
{
    public MyRegistry()
    {
        this.For<IUnitOfWork>().Use(new UnitOfWork("Connection1"));
        this.For<IDatabase2Service>().Use<Database2Service>().Ctor<IUnitOfWork>().Is(new UnitOfWork("Connection2"));
    }
}