동일한 인터페이스에서 파생 된 여러 유형이 있습니다. 그리고 난 후, 내가 어떤 문제없이 다음과 같이 유형을 해결할 수Unity : 현재 유형 인 '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
{
}
을 등록 유니티 IOC 컨테이너를 사용하고 있습니다.
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의 구성 파일 옵션을 사용하여 유형을 등록하십시오. 내가 갖고있는 목록에 따라 등록하고 싶습니다.
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
{
}
}
:> YourClass
이 작동 -