在运行时指定具有开放泛型和类型的Autofac

编程入门 行业动态 更新时间:2024-10-26 11:27:47
本文介绍了在运行时指定具有开放泛型和类型的Autofac的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

文档指出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:

structuremap.sourceforge/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

    本文发布于:2023-11-04 12:28:54,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1557941.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:类型   Autofac

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!