Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make setter injection in structuremap 3

I've been updated to structuremap 3, and now I can't use FillAllPropertiesOfType for setter injection.

Is it deprecated, what should I use instead?

like image 476
Bohdan Avatar asked Apr 09 '14 12:04

Bohdan


People also ask

How does setter injection work?

Setter injection is a dependency injection in which the spring framework injects the dependency object using the setter method. The call first goes to no argument constructor and then to the setter method. It does not create any new bean instance. Let's see an example to inject dependency by the setter method.

Why are setter injections better?

Setter-based DI helps us to inject the dependency only when it is required, as opposed to requiring it at construction time. Spring code generation library doesn't support constructor injection so it will not be able to create proxy. It will force you to use no-argument constructor.

When should setter injection be used?

Use Setter injection when a number of dependencies are more or you need readability. Use Constructor Injection when Object must be created with all of its dependency.


1 Answers

I just ran into the same problem. Looks like the new way to do this is via Registry.PoliciesExpression.

public interface IInjectable
{
    string Test();
}

public class Injectable : IInjectable
{
    public string Test()
    {
        return this.GetType().ToString();
    }
}

public class InjectTarget
{

    public IInjectable Injectable
    {
        get;
        set;
    }

}

static class Program
{
    static void Main()
    {

        ObjectFactory.Configure(x =>
        {
            //Setter injection
            x.Policies.FillAllPropertiesOfType<IInjectable>().Use<Injectable>();

            //Standard registration
            x.For<IInjectable>().Use<Injectable>();
            x.For<InjectTarget>().Singleton().Use<InjectTarget>();
        });

        var test = ObjectFactory.GetInstance<InjectTarget>();

        Console.WriteLine(test.Injectable.Test()); //WindowsFormsApplication3.Injectable
    }
}
like image 175
Xenolightning Avatar answered Oct 29 '22 17:10

Xenolightning