简体   繁体   English

Autofac使用开放式通用类解析开放式通用接口

[英]Autofac Resolve Open Generic Interface with Open Generic Class

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? 这不应该是微不足道的吗?

You have to use the RegisterGeneric method see Registration Concepts - Open Generic Components 您必须使用RegisterGeneric方法,请参阅注册概念 - 打开通用组件

Something like this should works : 这样的东西应该有效:

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

Yes it is trivial with container.RegisterGeneric: 是的,它对于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 (eg MyClass) followed by the type you it to be registered as (eg IMyInterface). 注册应该从想要注册的类型(例如MyClass)开始,然后是要注册的类型(例如IMyInterface)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 autofac解析所有类型的开放泛型类型? - autofac Resolve all types of open generic type? 使用Autofac注册并解析具有许多通用参数的开放通用类型 - Register and resolve open generic types with many generic parameters with Autofac 如何使用Autofac使用两个类型参数作为一个类型参数的接口注册和解析开放泛型 - How to register and resolve open generic with two type arguments as interface with one type argument using Autofac Autofac - 解析开放泛型类型以解析为派生类型 - Autofac - resolve open generic type to resolve to derived type Castle windsor解决了具有开放式通用和接口的阵列 - Castle windsor resolve array with open generic and interface Autofac:使用其类型参数的条件来解析开放式泛型 - Autofac: resolve an open generic with conditions on its type parameters Autofac注册错误:类型&#39;System.Collections.IEnumerable&#39;不是开放的通用类或接口类型 - Autofac registration error: The type 'System.Collections.IEnumerable' is not an open generic class or interface type 将Autofac开放通用接口注册转换为DryIoc注册 - Convert Autofac Open Generic Interface Registration to DryIoc Registration 用于开放通用的Autofac注册提供者 - Autofac register provider for open generic Autofac使用接口作为参数解析通用类型 - Autofac resolve generic type with interface as a param
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM