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

查看:31
本文介绍了使用 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天全站免登陆