gpt4 book ai didi

c#-4.0 - 在 CaSTLe.Windsor 中注册和解析命名实例

转载 作者:行者123 更新时间:2023-12-02 19:29:08 26 4
gpt4 key购买 nike

我似乎无法将正确的实例注入(inject)到类构造函数中。这是我正在尝试做的事情:

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;
}
}

有人能发现问题吗?

最佳答案

试试这个:

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")));

关于c#-4.0 - 在 CaSTLe.Windsor 中注册和解析命名实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15293598/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com