2010-05-26 30 views
3

我正在使用UnityContainer,並且我想註冊一個不是帶有類型的接口,而是另一個接口。 不幸的是,我無法清楚地做到這一點..RegisterType與UnityContainer中的接口

我有幾個常用接口,這是在一個界面統一,我需要在容器中註冊。該代碼是這樣的:

interface IDeviceImporter { 
    void ImportFromDevice(); 
} 

interface IFileImporter { 
    void ImportFromFile(); 
} 

interface IImporter : IDeviceImporter, IFileImporter { 
} 


class Importer1: IImporter { 
} 
class Importer2: IImporter { 
} 

當進入圖書館,我知道要使用的進口國,因此代碼如下:

var container = new UnityContainer(); 
if (useFirstImport) { 
    container.RegisterType<IImporter, Importer1>(); 
} else { 
    container.RegisterType<IImporter, Importer2>(); 
} 

,然後我想註冊IDeviceImporter這個特定的類和IFileImporter也。我需要這樣的東西:

container.RegisterType<IDeviceImporter, IImporter>(); 

但與代碼我得到一個錯誤:IImporter is an interface and cannot be constructed

我可以在條件內做到這一點,但它會複製粘貼。我能做

container.RegisterInstance<IDeviceImporter>(container.Resolve<IImporter>()); 

但它確實很髒。 任何人請,建議我的東西:)

回答

1

我使用ContainerControlledLifetimeManager,並用以下代碼結束:

var container = new UnityContainer(); 
System.Type importerType 
if (useFirstImport) { 
    importerType = GetType(Importer1); 
} else { 
    importerType = GetType(Importer2); 
} 

container.RegisterType(GetType(IImporter), importerType); 
container.RegisterType(GetType(IDeviceImporter), importerType); 
container.RegisterType(GetType(IFileImporter), importerType); 

但是,是的,最好的事情就是讓這樣的:

container.CreateSymLink<IDeviceImporter, IImporter>() 
4

那麼這取決於你使用的生命週期管理的類型。在這裏:

container.RegisterType<IImporter, Importer1>(); 

你用短暫的一個,這樣你就可以做到以下幾點:

var container = new UnityContainer(); 

if (useFirstImport) { 
    container.RegisterType<IImporter, Importer1>(); 
    container.RegisterType<IDeviceImporter, Importer1>(); 

} else { 
    container.RegisterType<IImporter, Importer2>(); 
    container.RegisterType<IDeviceImporter, Importer2>(); 
} 

而不用擔心錯誤的。 container.Resolve<IImporter>()將在每次通話中創建新實例,就像container.Resolve<IDeviceImporter>()一樣。

但是,如果您使用的是ContainerControlledLifetimeManager,那麼無論如何,您必須使用container.RegisterInstance<IDeviceImporter>(container.Resolve<IImporter>()),因爲Unity不提供其他方式來執行此操作。

這個功能真的很有趣,那將是非常好的,有像container.CreateSymLink<IDeviceImporter, IImporter>()但目前還沒有這樣的事情。