问题描述
文档指出Autofac支持开放式泛型,并且我能够在基本情况下进行注册和解析,如下所示:
The documentation states that Autofac supports open generics and I am able to register and resolve in a basic case like so:
注册:
builder.RegisterGeneric(typeof(PassThroughFlattener<>))
.As(typeof(IFlattener<>))
.ContainerScoped();
解决:
var flattener = _container.Resolve<IFlattener<Address>>();
上面的代码可以正常工作.但是,假设在运行时之前我不知道提供给IFlattener的类型,我想做这样的事情:
The above code works just fine. However, assuming that I will not know the type provided to IFlattener until runtime, I want to do something like this:
object input = new Address();
var flattener = (IFlattener)_container.Resolve(typeof(IFlattener<>), new TypedParameter(typeof(IFlattener<>), input.GetType()));
使用AutoFac可以吗?我是从以下使用StructureMap的想法中得到的:
Is this possible with AutoFac? I got the idea from the following using StructureMap:
http://structuremap.sourceforge.net/Generics.htm
我正在努力实现本文概述的相同目标.
I'm trying to achieve the same goal outlined in this article.
推荐答案
使用Autofac当然可以实现.在注册时间",这基本上就是您要做的:
This is certainly possible with Autofac. At "register time", this is what you basically do:
- 注册打开的通用类型(PassThroughFlattener<>)
- 注册任何特定类型(AddressFlattener)
- 注册一个可用于基于输入对象解析IFlattener的方法
在解决时间",您将执行以下操作:
At "resolve time", you will do:
- 解决方法
- 使用输入参数调用方法以解决IFlattener实现
这是一个(希望)工作的示例:
Here's a (hopefully) working sample:
var openType = typeof(IFlattener<>);
var builder = new ContainerBuilder();
builder.RegisterGeneric(typeof(PassThroughFlattener<>)).As(openType);
builder.Register<AddressFlattener>().As<IFlattener<Address>>();
builder.Register<Func<object, IFlattener>>(context => theObject =>
{
var closedType =
openType.MakeGenericType(theObject.GetType());
return (IFlattener) context.Resolve(closedType,
new PositionalParameter(0, theObject));
});
var c = builder.Build();
var factory = c.Resolve<Func<object, IFlattener>>();
var address = new Address();
var addressService = factory(address);
Assert.That(addressService, Is.InstanceOfType(typeof(AddressFlattener)));
var anything = "any other data";
var anyService = factory(anything);
Assert.That(anyService, Is.InstanceOfType(typeof(PassThroughFlattener<string>)));
这篇关于在运行时指定具有开放泛型和类型的Autofac的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!