具有参数的Dryioc寄存器接口/类构造函数

时间:2018-04-09 07:58:37

标签: dryioc

这是一个非常常见的问题,我已尝试过在dryioc网站上提出的建议以及SO上的其他一些示例。但是无法使其正常工作

Bcse很简单,我希望没有时间回复。

非常感谢

class Program
{
    static void Main(string[] args)
    {
        var mySample1 = new SampleOne {TestProperty = "Test1"};
        var mySample2 = new SampleTwo {TestProperty2 = "Test2"};


        using (var container = new Container())
        {
            //below Works with no parameter in constructor
            container.Register<ICustomerService, CustomerService>();

            //how do you register/singleton with class that has constructors need to pass(mySample1,mySample2)

        }
    }
}



public interface ICustomerService
{

}

public class CustomerService : ICustomerService
{

    private readonly SampleOne sample1;
    private readonly SampleTwo sample2;

    public CustomerService(SampleOne sampleOne,SampleTwo sampleTwo)
    {
        sample1 = sampleOne;
        sample2 = sampleTwo;
    }
}
public class SampleOne 
{
    public string TestProperty { get; set; }
}
public class SampleTwo
{
    public string TestProperty2 { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您可能忘记在容器中注册SampleOneSampleTwo了吗?

var mySample1 = new SampleOne {TestProperty = "Test1"};
var mySample2 = new SampleTwo {TestProperty2 = "Test2"};

container.UseInstance(mySample1);
container.UseInstance(mySample2);

// the rest is the same