0

我在配置要在类中用作服务中的参数构造函数的构造函数时遇到问题。我有两个使用同一个存储库的服务,存储库有两个构造函数,第一个由第一个服务使用,第二个由第二个服务使用。

我已经隔离了这个例子中的问题:

public interface IBookRepository { }

public class BookRepository : IBookRepository
{
    public BookRepository(string repositoryName, string dbName) { }
    public BookRepository(string repositoryName) { }
}

public interface IService1 { }

public class Service1 : IService1
{
    public Service1(IBookRepository repo) { }
}

public interface IService2 { }

public class Service2 : IService2
{
    public Service2(IBookRepository repo) { }
}

public class StrucutreMapRegistry : Registry
{
    public StrucutreMapRegistry()
    {
        var x = this;

        x.For<IService1>().Use<Service1>()
            .Ctor<IBookRepository>().Is<BookRepository>(c =>
            {
                new Container(x2 => x2.SelectConstructor(() => new BookRepository("")));
                c.Ctor<string>("repositoryName").Is("RepositoryForService1ToDefaultDatabase");
            });

        x.For<IService2>().Use<Service2>()
            .Ctor<IBookRepository>().Is<BookRepository>(c =>
            {
                new Container(x2 => x2.SelectConstructor(() => new BookRepository("", "")));
                c.Ctor<string>("repositoryName").Is("RepositoryForService2ToOtherDatabase");
                c.Ctor<string>("dbName").Is("OtherDatabase");
            });

    }
}

我使用“ new Container(x2 => x2.SelectConstructor(() => new BookRepository(""))); ”来选择构造函数,但此语句为所有用途全局选择构造函数。

如何为每个服务配置选择正确的构造函数?

提前致谢!

4

1 回答 1

0

像这样的东西:

    For<IBookRepository>()
        .Use<BookRepository>()
        .Named("SingleCtor").Ctor<string>().Is("rep name");

    For<IBookRepository>()
        .Use<BookRepository>()
        .Named("OtherCtor").Ctor<string>().Is("rep name").Ctor<string>().Is("db name");

    For<IService1>()
        .Use<Service1>()
        .Ctor<IBookRepository>().Is(x => 
        {
            return  x.GetInstance<IBookRepository>("OtherCtor");
        });

    For<IService2>()
        .Use<Service2>()
        .Ctor<IBookRepository>().Is(x => 
        {
            return  x.GetInstance<IBookRepository>("SingleCtor");
        });
于 2013-09-11T13:32:25.897 回答