2016-08-24 23 views
1

我有多种类型,从相同的接口派生。而且我使用Unity IOC容器如果我注册这些类型如下统一:当前类型“XXXXX”是一个接口,不能构建。你是否缺少类型映射?

 container.RegisterType<IService, ServiceA>("NameA"); 
     container.RegisterType<IService, ServiceB>("NameB"); 
     container.RegisterType<IService, ServiceC>("NameC"); 

然后我就可以如下解决类型没有任何问题,注册类型

public interface IService 
{ 
} 

public class ServiceA : IService 
{ 
} 

public class ServiceB : IService 
{ 

} 

public class ServiceC : IService 
{ 

} 

var service = container.Resolve<IService>("NameA"); 

但是我正在从外部获取需要注册容器的类型列表。 (让我们从文本文件中假设)。所以我只需要注册所提供列表中的那些类型。

public class Program 
{ 
    public static void Main() 
    { 
     // i will be getting this dictionary values from somewhere outside of application 
     // but for testing im putting it here 
     var list = new Dictionary<string, string>(); 
     list.Add("NameA", "ServiceA"); 
     list.Add("NameB", "ServiceB"); 
     list.Add("NameC", "ServiceC"); 


     var container = new UnityContainer(); 
     var thisAssemebly = Assembly.GetExecutingAssembly(); 

     //register types only that are in the dictionary 
     foreach (var item in list) 
     { 
      var t = thisAssemebly.ExportedTypes.First(x => x.Name == item.Value); 
      container.RegisterType(t, item.Key); 
     } 

     // try to resolve. I get error here 
     var service = container.Resolve<IService>("NameA"); 
    } 
} 

我得到异常

类型的未处理的异常 'Microsoft.Practices.Unity.ResolutionFailedException' 发生在 Microsoft.Practices.Unity.dll

其他信息:分辨率的依赖项失败,请键入= “ConsoleApplication1.IService”,name =“NameA”。

发生异常时:解决。

异常是:InvalidOperationException - 当前类型, ConsoleApplication1.IService是一个接口,不能被 构造。你是否缺少类型映射?


在异常时,容器是:

解决ConsoleApplication1.IService,NAMEA

对于一些合理的理由,我不想按照惯例选项可以使用统一的登记,或Unity的配置文件选项来注册类型。我想根据我的名单进行注册。

回答

0

你忘了指定的映射IYourInterface - > YourClass

这工作:

namespace ConsoleApplicationGrbage 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     var container = new UnityContainer(); 

     var list = new Dictionary<string, string>(); 
     list.Add("NameA", "YourClass"); 

     var thisAssemebly = Assembly.GetExecutingAssembly(); 
     var exT = thisAssemebly.ExportedTypes; 
     //register types only that are in the dictionary 
     foreach (var item in list) 
     { 
      var typeClass = exT.First(x => x.Name == item.Value); 
      var ivmt = Type.GetType("ConsoleApplicationGrbage.IYourInterface"); 
      // --> Map Interface to ImplementationType 
      container.RegisterType(ivmt, typeClass, item.Key); 
      // or directly: 
      container.RegisterType(typeof(IYourInterface), typeClass, item.Key);  
     } 

     var impl = container.Resolve<IYourInterface>("NameA"); 
    } 
} 


public interface IYourInterface 
{ 
} 

public class YourClass: IYourInterface 
{ 

} 

} 
相关问题