6

I want to inject an instance into structuremap on the fly (i.e. outside of a registry/configuration) that lives for the life of the request.

Currently I'm doing this in the HandleBeginRequest event of an IHttpModule:

container.Configure(x => x.For<IMyClass>()
  .LifecycleIs(Lifecycles.GetLifecycle(InstanceScope.PerRequest))
  .Use(new MyClass()));

However, if at some point in the application's life I do:

ObjectFactory.WhatDoIHave();

I see as many configured instances for IMyClass as there have been requests (or at least a significant amount).

Thinking about it, this sort of makes sense given the code I have.

Is there a better way to inject an instance into the container just for the life of the current request in a way that doesn't pollute the whole container?

Thanks

4
  • 3
    PerRequest means "per request for an instance from structuremap" - it has nothing to do with HTTP requests. Use one of the HTTP lifecycles. Commented Mar 31, 2011 at 12:47
  • 2
    Can you expand on why you want to do the registration in BeginRequest of every request? Registering it at app initialization time (with the correct lifecycle) will give you a new instance for each HTTP request. Is there some other detail you are not mentioning? Commented Mar 31, 2011 at 12:49
  • because i CREATE the instance on begin request, so i cant register it in the configuration Commented Apr 21, 2011 at 7:52
  • 1
    Right, so you register a lambda that will be evaluated at request time, and have it pull from some sort of factory. Which looks like what you did in your answer. Commented Apr 21, 2011 at 14:53

3 Answers 3

14

Your problem is that you're registering the type in the container once per request, which is building up on the registrations. Configuring the container should ideally be made once in the application's lifecycle - typically in the Application_Start event for web applications.

Structuremap allows you to specify a creational function that is invoked upon creating the object, which will let you configure advanced object creation steps.

Instead of your current call to Configure in the Begin_Request event, stick the following in the container configuration during Application_Start.

For<IMyClass>().HttpContextScoped().Use(() => new MyClass());

Notice the lambda in the Use method. The lambda can contain any logic needed in order to create the object and it will be invoked one per lifecycle (per request in the case of HttpContext lifecycle).

1
  • I create the MyClass instance on begin request, so I can't do this registration Commented Apr 21, 2011 at 8:05
7

I went with this in the end

For<IRequestContextStorage>()
    .HybridHttpOrThreadLocalScoped()
    .Use<RequestContextStorage>();

For<MyClass>()
    .Use(c => c.GetInstance<IRequestContextStorage>().Get<MyClass>());

...

public class RequestContextStorage : IRequestContextStorage
{
    readonly IDictionary<Type, object> hash;

    public RequestContextStorage()
    {
        this.hash = new Dictionary<Type, object>();
    }

    public T Get<T>() where T : class
    {
        if(this.hash.ContainsKey(typeof(T)))
            return this.hash[typeof (T)] as T;

        return null;
    }

    public void Set<T>(T instance)
    {
        this.hash[typeof (T)] = instance;
    }
}

...


static void HandleBeginRequest(object sender, EventArgs e) {

    ObjectFactory.Get<IRequestContextStore>().Set(new MyClass());

}
3

If you only have one container, and you have multiple requests, you will run into this problem. I would suggest managing the per request instances yourself by storing them in HttpContext.Items.

If you want to be able to access it through the container, create a gateway class that holds no state and pulls your per request dependency out of HttpContext for you. Register that in your container, and update dependencies on the per request object to you the gateway.

Update

I can't believe I overlooked this before, what you really want is to use HttpContextLifecycle, which will cache a given instance in the HttpContext.Items collection, where it will be available throughout your request. You will still have multiple instances active during concurrent requests, but StructureMap can figure out which one to return based on HttpContext.Current.

6
  • mega hax. thanks though. Do other containers have better support for this? Commented Mar 29, 2011 at 21:01
  • That is a good question, I am not aware of any mainstream containers that have support for this except using child containers. You could use child containers in StructureMap to do this, but I think it would be overkill. Commented Mar 29, 2011 at 21:18
  • Actually it looks like Castle Windsor can do this, although it looks a little complex (like Windsor itself) : kozmic.pl/2010/05/22/… Commented Mar 29, 2011 at 21:20
  • Yeah... I don't know what I was thinking when I wrote my answer, I have updated it with the right approach. All the major containers support some kind of HttpContext lifecyle approach. Commented Mar 30, 2011 at 18:14
  • I don't think the OPs main problem is the HttpContext lifecycle, but how it's currently used. The OP tries to apply InstanceScope.PerRequest which to my rememberance is the same as HttpContextLifecycle, but fails to register it just upon bootstrapping.
    – PHeiberg
    Commented Mar 31, 2011 at 11:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.