views:

83

answers:

2

I have a httpHandler and using Unity 2 I would like to inject a dependency into my HttpHandler.

My code looks like:

public class MyHandler : BaseHandler
{

    public MyHandler()
    {
    }

    public IConfigurationManager Configuration
    {
        get;
        set;
    }

    ...
}

Using the web.config I would configure it like this (left out the rest of the config for simplicity) :

<type type="MyHandler">
   <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">
      <property name="Configuration" propertyType="IConfigurationManager">
        <dependency/>
      </property>
   </typeConfig>
</type>

How would I go about doing the same thing using fluent syntax? Everything I have tried so far leaves the property set to null when the handler fires.

Thanks

A: 

You have to call the ConfigureInjectionFor method.

myContainer.Configure<InjectedMembers>()
    .ConfigureInjectionFor<MyHandler>(
            new InjectionProperty("Configuration", 
                                  new ResolvedParameter<IConfigurationManager>())
                                 )
            )

EDIT:

Here is an example of Handler factory. It allow you to create your handler

 class HandlerFactory : IHttpHandlerFactory
    {
        public IHttpHandler GetHandler(HttpContext context, string requestType, String url, String pathTranslated)
        {
            return MyContainerProvider.Container.Resolve<MyHandler>();
        }
        public void ReleaseHandler(IHttpHandler handler)
        {
        }
        public bool IsReusable
        {
            get { return false; }
        }
    }

Then, you have to register the factory in your web application (to allow IIS to find it). You can find more details here.

onof
Onof, for some reason this does not work for me. I even tried the [Dependency] attribute on the Configuration property. Injection inside controllers seem to work just fine but I can't get it to work inside a httphandler with Unity.
Thomas
This is enough to configure the container. You need to build up the handler, for example registering an HttpHandlerFactory
onof
Onof, do you have an example of this? And also, why do I have to build up the handler? This is fairly new to me so any help is appreciated.
Thomas
I edited my answer
onof
A: 

ConfigureInjectionFor has been obsolete since Unity 1.2 was released.

This should work:

container.RegisterType<MyHandler>(
    new InjectionProperty("Configuration"));
Chris Tavares