简体   繁体   English

如何使autofac实时解析带有参数的构造函数?

[英]How to make autofac resolve constructor with parameters in real time?

Easy example for understanding what i mean: 理解我的意思的简单例子:

public interface IWarrior
{
    string GetName();
}

public class HumanWarrior : IWarrior
{
    string _name;
    public HumanWarrior(string name)
    {
        _name = name;
    }

    public string GetName()
    {
        return _name;
    }
}

public class  AnimalWarrior : IWarrior
{
    string _name;
    public AnimalWarrior(string name)
    {
        _name = name;
    }

    public string GetName()
    {
        return "animal" + _name;
    }
}

In my code i use it like: 在我的代码中,我像这样使用它:

    ...code
    string warriorName = "Glark";
    WarriorService warriorService = new WarriorService(new HumanWarrior(warriorName));
   ...code

I know how i can use Autofac to resolve IWarrior if nested classes have empty constructors; 我知道如果嵌套类的构造函数为空,如何使用Autofac解析IWarrior。 But what if i need to create example of IWarrior, that needs "name" parameter, and i cant configure value of this parameter in Autofac settings. 但是,如果我需要创建IWarrior的示例,那需要“名称”参数,并且无法在Autofac设置中配置此参数的值怎么办?

I would not do it like that, that's not the point of an IOC container like Autofac. 我不会那样做,这不是Autofac这样的IOC容器的重点。

What I would do is create a public string Name {get; set;} 我要做的是创建一个public string Name {get; set;} public string Name {get; set;} property or a function public void Init(string name) { ... } public string Name {get; set;}属性或函数public void Init(string name) { ... }

Edit: This is how I would build it 编辑:这就是我将如何构建它

public class HumanWarrior : IWarrior
{
    public string Name { get; set; }
}

Or something like this: 或类似这样的东西:

    public class HumanWarrior : IWarrior
    {
        public string Name { get; private set; }

        public void Init(string name)
        {
            Name = name;
        }
    }

With the interface like this: 使用这样的界面:

public interface IWarrior
{
    string Name { get; set; }
}

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

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