Search code examples
c#inversion-of-controlstructuremapconstructor-injection

Passing an object to class constructor in runtime using structuremap


I have following class in my project:

public partial class MyForm : BaseForm, IMyInterface
{
    public MyForm(MyDto dto)
    {
        _dto = dto;
        InitializeComponent();
    }
}

and use following code to register in structuremap:

ObjectFactory.Configure(x => x.For<IMyInterface>()
            .Use<MyForm>()
            .Ctor<MyDto>("MyDto"));

When I want to use the class, I used following code:

var dto = new MyDto(){
            Id = 43,
            From = DateTime.Now(),
            To = DateTime.Now().AddDays(1)};

IMyInterface frm = ObjectFactory.Container.With("MyDto")
                   .EqualTo(dto).GetInstance<IMyInterface>();

But the passed dto value to the frm isn't same as I passed(Id = 43, ....), it is the default value of MyDto class(Id = 0, ...). Where is the problem?


Solution

  • I used following code to solve the problem:

    IMyInterface frm = ObjectFactory.Container
                       .With<MyDto>(dto)
                       .GetInstance<IMyInterface>();