我想在我的应用程序中使用Ninject自定义作用域,以便将DbContext的单个激活作用域包含到我的核心域处理程序中。然而,我遇到了麻烦,因为CommandScope对象实现了Ninject的一部分INotifyWhenDisposed接口,并且我不想在我的域中依赖Ninject。为确定性处理注入Ninject作用域对象
我已经尝试了许多其他方式来获得依赖到代码中,没有成功,包括使用Ninject工厂来公开一个IScopeFactory和一个Func依赖。在后一种情况下,问题是(我认为)Ninject不会连接INotifyWhenDisposed.Dispose事件,因为绑定目标是Func而不是IDisposable本身。
无论如何,这是我想要实现的代码。
的IoC
Kernel
.Bind<MyDbContext>()
.ToSelf()
.InScope(x => CommandScope.Current)
.OnDeactivation(x => x.SaveChanges());
CommandScope
public class CommandScope : INotifyWhenDisposed
{
public event Dispose;
public bool IsDisposed { get; private set; }
public static CommandScope Current { get; private set; }
public static CommandScope Create()
{
CommandScope result = new CommandScope();
Current = result;
return result;
}
public void Dispose()
{
IsDisposed = true;
Current = null;
Dispose?.Invoke(this, EventArgs.Empty);
}
}
里面我的域名......
public class Pipeline<TRequest, TResponse>
{
readonly IRequestHandler<TRequest, TResponse> innerHandler;
public Pipeline(IRequestHandler<TRequest, TResponse> handler)
{
innerHandler = handler;
}
public TResponse Handle(TRequest request)
{
using(CommandScope.Create())
{
handler.Handle(request);
}
}
}
但是,您的Pipeline类是一些基础代码,因此您可以将它提取到与包含域逻辑的项目不同的项目。或者你还有其他问题? –