我有一個這樣的安裝程序:如何根據Castle Windsor中的泛型類型參數來解析服務?
public void Install(IWindsorContainer container, IConfigurationStore store) {
//Services
container.Register(
Classes.FromAssemblyNamed(ASSEMBLY_NAME)
.BasedOn<IService>()
.WithServiceFirstInterface()
.LifestyleTransient());
//Repository
container.Register(
Component.For(typeof(IRepository<>))
.ImplementedBy(typeof(Repository<>))
.LifestyleTransient());
//Contexts
container.Register(
Component.For(typeof(Context<IGlobalObject>))
.ImplementedBy(typeof(GlobalContext<>)).LifestyleTransient());
}
庫是一個開放通用的,它注入了上下文構造函數,它是圍繞EF的DbContext的包裝,但需要一個類型參數指示數據庫它需要連接。我的想法是,我有幾個DbContexts,因爲我需要連接到多個數據庫,並且我想windsor根據傳遞給存儲庫的類型參數來解析適當的DBcontext。
的庫類型參數約束以下(GlobalObject和GlobalContext中是指用1組這樣的數據庫相關聯的類型):
public interface IGlobalObject : IObject
{}
public interface IObject
{
int Key { get; set; }
}
然而,溫莎無法解決的情況下,我不能工作了,爲什麼?它已註冊並位於容器中,但無法解析。
編輯:
代碼GlobalContext中:
public class GlobalContext<T> : Context<T>
where T : IGlobalObject
{
private const string GLOBAL_CSTR = "Global";
public GlobalContext() : base(ConfigurationManager.ConnectionStrings[GLOBAL_CSTR].ConnectionString) {}
public DbSet<Company> Companies { get; set; }
public DbSet<ConnectionString> ConnectionStrings { get; set; }
public DbSet<Server> Servers { get; set; }
}
語境:
//Wrapper around dbcontext which enforces type
public abstract class Context<T> : DbContext where T : IObject
{
protected Context() {}
protected Context(string connectionString) : base(connectionString){}
}
編輯2:
如果我指定的具體類型前夕它的工作原理很明顯,所以很明顯與界面上的匹配有關。
//Contexts
container.Register(
Component.For(typeof(Context<Server>))
.ImplementedBy(typeof(GlobalContext<Server>)).LifestyleTransient());
這完全有道理,但可悲的是沒有工作。我已經添加了Context和GlobalContext的代碼。乾杯 – 2013-02-21 10:09:13
好的 - 我想我現在明白了,我做了一個小的修改 - 刪除了一般的論點。 – 2013-02-21 11:01:48