4

我似乎无法将正确的实例注入到类 ctor 中。这是我正在尝试做的事情:

class Program
{
    static void Main(string[] args)
    {
        WindsorContainer container = new WindsorContainer();
        container.Register(
            Component.For<ISessionFactory>()
                .UsingFactoryMethod(() => GetSessionFactory("1"))
                .Named("1"),
            Component.For<ISessionFactory>()
                .UsingFactoryMethod(() => GetSessionFactory("2"))
                .Named("2"));

        container.Register(
            Component.For<IRepository>()
                .ImplementedBy<Repository>()
                .DependsOn(container.Resolve<ISessionFactory>("1")),
            Component.For<IReadOnlyRepository>()
                .ImplementedBy<ReadOnlyRepository>()
                .DependsOn(container.Resolve<ISessionFactory>("2")));

        var connectionString1 = container.Resolve<IRepository>().Factory.ConnectionString;
        var connectionString2 = container.Resolve<IReadOnlyRepository>().Factory.ConnectionString;

        //These should not be equal!!!
        Console.WriteLine(connectionString1);
        Console.WriteLine(connectionString2);
    }

    public static SessionFactory GetSessionFactory(string connectionString)
    {
        return new SessionFactory { ConnectionString = connectionString };
    }

    public static bool Blah(Type accepted)
    {
        int d = 3;
        return true;
    }
}

public interface ISessionFactory
{
    string ConnectionString { get; set; }
}

public class SessionFactory : ISessionFactory
{
    public string ConnectionString { get; set; }
}

public interface IRepository
{
    ISessionFactory Factory { get; set; }
}

public class Repository : IRepository
{
    public ISessionFactory Factory { get; set; }

    public Repository(ISessionFactory factory)
    {
        this.Factory = factory;
    }
}

public interface IReadOnlyRepository
{
    ISessionFactory Factory { get; set; }
}

public class ReadOnlyRepository : IReadOnlyRepository
{
    public ISessionFactory Factory { get; set; }

    public ReadOnlyRepository(ISessionFactory factory)
    {
        this.Factory = factory;
    }
}

谁能发现问题?

4

1 回答 1

8

试试这个:

container.Register(
   Component.For<ISessionFactory>()
       .UsingFactoryMethod(() => GetSessionFactory("1"))
       .Named("1"),
   Component.For<ISessionFactory>()
       .UsingFactoryMethod(() => GetSessionFactory("2"))
       .Named("2"),
   Component.For<IRepository>()
       .ImplementedBy<Repository>()
       .DependsOn(Dependency.OnComponent(typeof(ISessionFactory),"1")),
   Component.For<IReadOnlyRepository>()
       .ImplementedBy<ReadOnlyRepository>()
       .DependsOn(Dependency.OnComponent(typeof(ISessionFactory), "2")));
于 2013-03-08T16:54:58.910 回答