【发布时间】:2014-04-15 10:32:23
【问题描述】:
我有以下代码来构建依赖项:
private static void InitializeContainer(HttpConfiguration config)
{
var builder = new ContainerBuilder();
var controllers = AssemblyUtils.GetAssemblies(true);
controllers.Add(Assembly.GetExecutingAssembly());
builder.RegisterApiControllers(controllers.ToArray()).PropertiesAutowired();
builder
.RegisterAssemblyTypes(
new List<Assembly>(AssemblyUtils.GetAssemblies(false))
{
Assembly.GetExecutingAssembly()
}.ToArray())
.Where(t =>
t.GetCustomAttributes(typeof(IocContainerMarkerAttribute), false).Any() ||
t.IsSubclassOf(typeof(HandlerAspectAttribute)) ||
typeof(ICoreContract).IsAssignableFrom(t))
.AsImplementedInterfaces().InstancePerDependency()
.PropertiesAutowired().OwnedByLifetimeScope();
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver =
new AutofacWebApiDependencyResolver(container);
config.DependencyResolver =
GlobalConfiguration.Configuration.DependencyResolver;
}
处理程序:
public class ArchieveDocumentCommandHandler
: IHandler<ArchieveDocumentCommand>, IDisposable
{
public IServiceMessageDispatcher Dispatcher { get; set; }
public IDocumentRepository DocumentRepository { get; set; }
public IFileSystemProvider FileSystemProvider { get; set; }
public ICoreSettingRepository CoreSettingRepository { get; set; }
public void Handles(ArchieveDocumentCommand message) { }
public void Dispose() { }
}
但不知何故,Autofac 并没有在请求完成后调用对象中的Dispose 方法。我读到了生命周期范围,但由于在这种情况下是 Autofac 管理范围,所以我无法理解发生了什么。
我在这里做错了吗?
更新
public class CommandsController : ApiController
{
[HttpPost]
public HttpResponseMessage Deliver()
{
...
var handler = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ICommandValidator<>).MakeGenericType(message.GetType()));
if (handler == null)
{
return new Dictionary<string, string>();
}
return (Dictionary<string, string>)handler.GetType()
.InvokeMember("ValidateCommand", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, handler, new object[] { message });
}
}
另外,我使用的 autofac web api 版本是:3.1.1 这也破坏了一些现有的功能:
这样的控制器:
public class AProtectedReadModelController : ApiController
{ }
public class AssessmentController : AProtectedReadModelController
{
[Route("queries/risk/assessment")]
[HttpGet]
public ProcessInitialScreenModel GetProcessInitialScreen()
{
return ...;
}
}
未加载。
【问题讨论】:
-
您能否确认 Autofac 正在 WebAPI 之外正确处理处置?
-
我为什么要这样做?我需要它来使用 WebAPI。
-
你能告诉我们什么正在消耗处理程序以及它的生命周期范围是什么?我很好奇对象是否保持活力,因为依赖它的东西正在保持活力。例如,如果使用处理程序的事物是单例,则处理程序将在根生命周期范围内解析,并且在根范围清理之前不会被清理。
-
@TravisIllig 在通用控制器中使用的处理程序将发布代码示例。谢谢
标签: c# dependency-injection autofac asp.net-web-api2