简体   繁体   English

Unity:在xml配置文件中将参数传递给自定义生命周期构造函数

[英]Unity: pass parameters to custom lifetime constructor, in xml configuration file

I wrote my CustomLifetimeManager like this: 我这样写了CustomLifetimeManager:

public class CustomLifetimeManager <T> : LifetimeManager
{
    private readonly string _arg;

    public CustomLifetimeManager(string arg)
    {
      _arg = arg;
    }
}

Now, it works easy configuring the container programmatically, but how add it in configuration file like the following? 现在,它可以轻松地以编程方式配置容器,但是如何将其添加到配置文件中,如下所示?

<type type="myTime"
      mapTo="myImpl">
      <lifetime type="CustomLifetimeManager"/>
</type>

You need to add a second class: A TypeConverter. 您需要添加第二个类:TypeConverter。 This class is responsible for taking a string and turning it into whatever type you want. 此类负责将字符串转换为所需的任何类型。 Once you implement it, you can then do something like this in your config file: 一旦实现,就可以在配置文件中执行以下操作:

<register type="MyType" mapTo"MyImpl">
  <lifetime typeConverter="CustomLifetimeManagerConverter" value="arg" />
</register>

and from there it should just work (assuming the config can find the type converter like any other type). 并从那里开始工作(假设配置可以像其他类型一样找到类型转换器)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM