1
public class StoreDetails
{
    public int StoreId { get; set; }
}

I want to create an instance of StoreDetails for per request to Web API. This instance will be used as dependency for various other classes in project. Also I want to set value of "StoreId" property to HttpContext.Current.Request.Headers["StoreId"]

I am using Unity as container with help of following libraries: Unity 3.5.1404.0 Unity.AspNet.WebApi 3.5.1404.0

I have following method to register types

public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterInstance<StoreDetails>(/* how to provide some method to inject required StoreId from HttpContext.Current.Request.Headers["StoreId"] per request */);
    }
1
  • See also this answer. Commented Aug 28, 2015 at 13:25

1 Answer 1

2

I figured out how to do this on my own.

public static void RegisterTypes(IUnityContainer container)
    {
        // Some other types registration .

        container.RegisterType<StoreDetails>(
            //new PerResolveLifetimeManager(), 
            new InjectionFactory(c => {
                int storeId;
                if(int.TryParse(HttpContext.Current.Request.Headers["StoreId"], out storeId)) {
                    return new StoreDetails {StoreId = storeId};
                }
                return null;
            }));
    }
Sign up to request clarification or add additional context in comments.

1 Comment

This would create an instance, not per HTTP request, but per each call to the Unity container to resolve the StoreDetails type. Each of those instances will have the same StoreId value for a given HTTP request, but the objects themselves will be separate instances. Whether that proves to be problematic will depend on what StoreDetails does, and how it's used.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.