0

我有一個這樣的安裝程序:如何根據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()); 

回答

0

這看起來像一個問題,對我說:

//Contexts 
container.Register(
    Component.For(typeof(Context<IGlobalObject>)) 
     .ImplementedBy(typeof(GlobalContext<>)).LifestyleTransient()); 

在這裏,你是說 - 當有人問上下文注入GlobalContext中<> - 問題是溫莎是如何打算知道是什麼GlobalContext的泛型參數是。

它很難看到沒有看到你的GlobalContext中的對象,但它應該是:

container.Register(
    Component.For(typeof(Context<>)) 
     .ImplementedBy(typeof(GlobalContext<>)).LifestyleTransient()); 
+0

這完全有道理,但可悲的是沒有工作。我已經添加了Context和GlobalContext的代碼。乾杯 – 2013-02-21 10:09:13

+0

好的 - 我想我現在明白了,我做了一個小的修改 - 刪除了一般的論點。 – 2013-02-21 11:01:48

0

這是不是一個真正的直接回答你的問題。但我覺得這種做法可能是錯誤的。

考慮到您的存儲庫是由一個通用的基地Repository<>實施我不能看到一個乾淨的方式將泛型類型與正確的上下文相關聯。我認爲您可能需要切換到「風格」的存儲庫,並注入明確的上下文,並且/或者在註冊上下文時更加詳細。

相關問題