2011-04-01 39 views
2

我有一個接口:Unity Framework可以在不同於給定接口的不同名稱空間中實例化一個類嗎?

namespace IF.Model 
{ 
    public interface IAllocationGroupRepository 
    { 
    } 
} 

和類接口的工具:在代碼

using IF.Model; 
namespace IF.Repository 
{ 
    public class AllocationGroupRepository : IAllocationGroupRepository 
    { 
    } 
} 

在統一框架電話,我可以.RegisterType()對他們倆的:

IUnityContainer container = new UnityContainer(); 
container.RegisterType<IAllocationItemRepository, AllocationItemRepository>(); 
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>(); 

和.Resolve()的作品,並給我一個新的AllocationItemRepository對象。

但是,當我嘗試調用決心和映射住在app.config文件,我得到這個錯誤:

「目前的類型,IF.Model.IAllocationItemRepository,是一個接口,不能構建你缺少一個類型映射嗎?「

這裏是我的app.config文件看起來像:

<unity> 
     <containers> 
      <container> 
       <types> 
        <type 
         type="IF.Model.IAllocationGroupRepository, IF.Model" 
         mapTo="IF.Repository.AllocationGroupRepository, IF.Repository" /> 
       </types> 
      </container> 
     </containers> 
    </unity> 

這裏是代碼的樣子試圖調用.Resolve()使用的是什麼是在App .config文件:

IUnityContainer container = new UnityContainer(); 
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); 
section.Containers.Default.Configure(container); 
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>(); 

正如你所看到的,這是很基本的東西。給定一個接口,將其解析爲類。它在內聯時工作,但在嘗試從app.config文件執行時失敗。

我在這裏錯過了什麼?

謝謝, 邁克

回答

0

嘗試使用該呼籲的命名空間中的一個參數的別名。

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> 
    <alias alias="IAllocationGroupRepository" type="IF.Model.IAllocationGroupRepository, IF.Model, Version=1.0.0.0, Culture=neutral"/> 
    <alias alias="AllocationGroupRepository" type="IF.Repository.AllocationGroupRepository, IF.Repository, Version=1.0.0.0, Culture=neutral"/> 

    <container> 
     <register type="IAllocationGroupRepository" mapTo="AllocationGroupRepository"/> 
    </container> 
</unity> 

但是,爲什麼要將存儲庫接口放在模型名稱空間中?作爲開發人員首次查看代碼的開發人員是否期望在Model命名空間或Repository命名空間中找到IRepository接口?

+0

Craig,感謝您的代碼。不幸的是,它沒有奏效。我認爲這是新的Unity 2.0配置文件格式,而且我仍然使用Unity庫4.1來使用Unity。無論哪種方式,我確實在Unity 4.1中嘗試了別名,而且我仍然遇到同樣的錯誤。至於爲什麼我的模型中有我的Repository接口:http://martinfowler.com/eaaCatalog/separatedInterface.html。我不知道這是否正確,我想我可以移動界面。我正在使用這些Repository接口來注入我的Model代理以進行延遲加載。再次,不太確定是否正確。 – 2011-04-04 01:34:03

0

我假設你有統一的參考,那麼你需要定義你的部分名稱和它的庫。像這樣:

<?xml version="1.0"?> 
<configuration> 
    <configSections> 
<section name="mySectionName" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/> 
    </configSections> 
    <mySectionName> 
    <typeAliases> 
    ... 
相關問題