使用Autofac解决通用接口 [英] Resolving Generic Interface with Autofac

查看:192
本文介绍了使用Autofac解决通用接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码,如何在autofac中解析正确的SomeInstance?

Given the following code, how do I resolve the right SomeInstance in autofac?

public class BaseClass {}

public class SubClass1 : BaseClass {}

public class SubClass2 : BaseClass {}

public interface IGenericInterface<T> where T : BaseClass {}

public class SomeInstance1<T> : IGenericInterface<T> where T : SubClass1

public class SomeInstance2<T> : IGenericInterface<T> where T : SubClass2

我想根据子类上泛型的类型选择SomeInstance1或2.

I want to choose SomeInstance1 or 2 based on the type of of the generic on the sub classes.

因此,例如,我有一个子类集合(SubClass1、2 ...),并且在对其进行迭代时,我想选择正确的SomeInstance类.

So for example I have a collection of sub classes (SubClass1, 2....) and while iterating over them I want to choose the right SomeInstance class.

推荐答案

Autofac支持开放的泛型.如果在编译时已知泛型类型,则可以使用以下代码:

Autofac supports open generics. You can use the following code if generics type is known at compile time:

var builder = new ContainerBuilder();

builder.RegisterGeneric(typeof(SomeInstance1<>))
  .As(typeof(IGenericInterface<>));              

var container = builder.Build();

var instance1 = container.Resolve<IGenericInterface<SubClass1>>();

Assert.IsInstanceOfType(typeof(SomeInstance1<SubClass1>), instance1);

如果直到运行时才知道类型参数(如果要遍历类型集合,则可能是这种情况),则可以使用MakeGenericType构建类型:

If type parameter is not known until runtime (which is likely your case if you want to iterate through collection of types) then you can build your type using MakeGenericType:

        var typeInRuntime = typeof (SubClass1);
        var instance1 = container.Resolve(typeof(IGenericInterface<>).MakeGenericType(typeInRuntime));

这篇关于使用Autofac解决通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆