public class StoreDetails
{
public int StoreId { get; set; }
}
我想为每个Web API请求创建一个StoreDetails实例。此实例将用作项目中各种其他类的依赖项。
另外,我想将“StoreId”属性的值设置为HttpContext.Current.Request.Headers["StoreId"]
我在以下库的帮助下使用Unity作为容器: Unity 3.5.1404.0 Unity.AspNet.WebApi 3.5.1404.0
我有以下注册类型的方法
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 */);
}
答案 0 :(得分:2)
我想出了如何自己做这件事。
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;
}));
}