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 */);
    }
AviD
  • 66
  • 7

1 Answers1

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;
            }));
    }
AviD
  • 66
  • 7
  • 2
    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. – Snixtor Aug 08 '16 at 01:55