views:

16

answers:

1

I have the following code:

Unity Container:

Settings settings = CreateSettings();

container.RegisterInstance(settings)
         .RegisterType<MyHttpHandler>(new InjectionProperty[]
             {
                 // How do I tell Unity to inject my settings created above?
                 new InjectionProperty("Settings", new ResolvedParameter(????))
             });

MyHttpHandler:

public class MyHttpHandler: IHttpHandler
{
    public MyHttpHandler()
    {
        IoC.Inject(this);
    }

    public Settings Settings
    {
        get;
        set;
    }
}

How do I tell Unity to inject the settings? This works just fine with interfaces but not sure how to proceed here.

Any help is appreciated.

A: 

It just goes off the type. You've registered an instance for the Settings class, so you just need to tell it to inject that type:

container.RegisterInstance(settings)
    .RegisterType<MyHttpHandler>(
        new InjectionProperty("Settings", new ResolvedParameter<Settings>());

(Note that you don't need the extra array, RegisterType takes a variable parameter list.)

Since this is a common requirement, there are shorthands you can use. First off, if you're resolving a dependency and you just need the default (non-named) registration, you don't need to use ResovledParameter, you can just pass the type object:

container.RegisterType(settings)
    .RegisterType<MyHttpHandler>(
        new InjectionProperty("Settings", typeof(Settings));

But, we can also go simpler than that. If you're using the default for a property based on the type, you don't need to pass the value at all - the container will simply use the type of the property. So you can just say:

container.RegisterType(settings)
    .RegisterType<MyHttpHandler>(
        new InjectionProperty("Settings"));

and the container will figure it out.

Chris Tavares