Dependency Injection with the OpenNETCF.IoC Framework

The OpenNETCF.IoC Framework support injection of dependency objects through Constructor or Property injection. Field injection is not recommended, and so I didn't add support for it. Just like the SCSF, automatic injection is supported only on the Services collection to prevent any ambiguity as to which instance should be injected (the Services collection only allows a single object per reistered type). Again like the SCSF, automatic injection is provided via the ServiceDependency attribute.

Assume we have two classes, Foo and Bar. Bar is a service that implemets IBar, and each instance of Foo needs a reference to the registered IBar service. This can be achieved through automatic injection.

Constructor Injection

Foo would define an injection constructor:

    public class Foo
    {
        public IBar Bar { get; set; }

        [InjectionConstructor]
        public Foo([ServiceDependency]IBar bar)
        {
            // bar is fully constructed here and can be used and/or stored
            Bar = bar;
        }
    }


When the Framework is used to create an instance of Foo, the IBar instance will get injected automatically:

    IBar myBar = RootWorkItem.Services.AddNew<Bar, IBar>();
    Foo instance = RootWorkItem.Items.AddNew<Foo>("My Foo");

    // at this point instance.Bar == myBar

Property Injection

Foo would define an Property with a ServiceDependency. Note that this proerty does not have to be public, so injection can still happen while hiding the member from consuming objects.

    public class Foo
    {
        [ServiceDependency]
        IBar Bar { get; set; }

        public Foo()
        {
          // the Bar property will not be set until *after* this constructor exits
        }
    }


When the Framework is used to create an instance of Foo, the IBar instance will get injected automatically:

    IBar myBar = RootWorkItem.Services.AddNew<Bar, IBar>();
    Foo instance = RootWorkItem.Items.AddNew<Foo>("My Foo");

    // at this point instance.Bar == myBar

Last edited Dec 1, 2009 at 8:24 PM by ctacke, version 2

Comments

No comments yet.