Search code examples
dryioc

Dryioc register interface/class constructors with params


This is a very common questions and I have tried what is suggested on the dryioc website and some other samples on SO.but cannot make it work

Bcse its so simple I hope it will take somebody no time to reply.

Many thanks

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; }
}

Solution

  • May be you forgot to register SampleOne and SampleTwo in container?

    var mySample1 = new SampleOne {TestProperty = "Test1"};
    var mySample2 = new SampleTwo {TestProperty2 = "Test2"};
    
    container.UseInstance(mySample1);
    container.UseInstance(mySample2);
    
    // the rest is the same