I (CommonServiceLocator package yoluyla) ASP.NET MVC'ın Bağımlılık Çözücü ile StructureMap kaydedilmesi için bulabildiğim this was the best guide, bu soruya kendimi ran olması.
Yukarıdaki makalenin çözümünü kopyaladım ve yapıştırdım, ancak bu makalenin orijinal makalesinde sağladığı yararları gözden geçirmenizi öneririz.
public class StructureMapDependencyResolver : ServiceLocatorImplBase
{
private const string StructuremapNestedContainerKey = "Structuremap.Nested.Container";
public IContainer Container { get; set; }
private HttpContextBase HttpContext
{
get
{
var ctx = Container.TryGetInstance<HttpContextBase>();
return ctx ?? new HttpContextWrapper(System.Web.HttpContext.Current);
}
}
public IContainer CurrentNestedContainer
{
get { return (IContainer)HttpContext.Items[StructuremapNestedContainerKey]; }
set { HttpContext.Items[StructuremapNestedContainerKey] = value; }
}
public StructureMapDependencyResolver(IContainer container)
{
Container = container;
}
protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
{
return (CurrentNestedContainer ?? Container).GetAllInstances(serviceType).Cast<object>();
}
protected override object DoGetInstance(Type serviceType, string key)
{
var container = (CurrentNestedContainer ?? Container);
if (string.IsNullOrEmpty(key))
{
return serviceType.IsAbstract || serviceType.IsInterface
? container.TryGetInstance(serviceType)
: container.GetInstance(serviceType);
}
return container.GetInstance(serviceType, key);
}
public void Dispose()
{
if (CurrentNestedContainer != null)
{
CurrentNestedContainer.Dispose();
}
Container.Dispose();
}
public IEnumerable<object> GetServices(Type serviceType)
{
return DoGetAllInstances(serviceType);
}
public void DisposeNestedContainer()
{
if (CurrentNestedContainer != null)
CurrentNestedContainer.Dispose();
}
public void CreateNestedContainer()
{
if (CurrentNestedContainer != null) return;
CurrentNestedContainer = Container.GetNestedContainer();
}
}
Sonra şöyle çözümleyicinizi ayarlayabilirsiniz:
public class MvcApplication : System.Web.HttpApplication
{
public static StructureMapDependencyResolver StructureMapResolver { get; set; }
protected void Application_Start()
{
...
// Setup your Container before
var container = IoC.Initialize();
StructureMapResolver = new StructureMapDependencyResolver(container);
DependencyResolver.SetResolver(StructureMapResolver);
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
StructureMapResolver.CreateNestedContainer();
}
protected void Application_EndRequest(object sender, EventArgs e)
{
StructureMapResolver.DisposeNestedContainer();
}
}
yapılandırması bu tip büyük bir sonuç, konteyner sonunda imha edilir, istek başına yeni bir çocuk konteyneri almaya olduğunu her isteğin