Autofac Resolve Open Generic Interface with Open Generic Class

痞子三分冷 提交于 2019-12-07 17:35:15

问题


So I have an interface and class:

public interface IMyInterface<T> where T : ISomeEntity {}

public class MyClass<T> : IMyInterface<T>
    where T : ISomeEntity {}

I will have some class that calls for it:

public class SomeClass : ISomeClass
{
    public SomeClass (IMyInterface<AuditEntity> myInterface) {}
}

I've done all sorts of things to get it to register the open generic interface and class with no luck.

I just want to say something like:

container.RegisterType(typeof(MyClass<>)).As(typeof(IMyInterface<>));

It would be annoying if I have to go through and explicitly do something like:

container.RegisterType<MyClass<AuditEntity>>().As<IMyInterface<AuditEntity>>();

Shouldn't this be trivial?


回答1:


You have to use the RegisterGeneric method see Registration Concepts - Open Generic Components

Something like this should works :

builder.RegisterGeneric(typeof(MyClass<>)).As(typeof(IMyInterface<>)); 



回答2:


Yes it is trivial with container.RegisterGeneric:

container.RegisterGeneric(typeof(MyClass<>)).As(typeof(IMyInterface <>));

You also seem to have your interface and class switched in the examples in your question. The registration should start with the type to want to register (e.g. MyClass) followed by the type you it to be registered as (e.g. IMyInterface).



来源:https://stackoverflow.com/questions/31588094/autofac-resolve-open-generic-interface-with-open-generic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!