我想我知道你想做什么。我在同一条船上,正在尝试提出解决方案。
我的服务层对即将到来的请求执行操作,它的作用取决于内容。它将它传递给一系列责任类。我希望在调用的服务方法的生命周期内将相同的上下文传递给所有类
您可以指定 PerResolveLifetimeManager。到目前为止,它似乎正在处理我的测试用例:
服务等级:
public interface IServiceClass
{
void DoService();
}
class ServiceClass : IServiceClass
{
private IHandler Handler { get; set; }
public ServiceClass(IHandler handler)
{
Handler = handler;
}
public void DoService()
{
Handler.HandleRequest();
}
}
IHandler 由两个类实现,并执行责任链模式:
public interface IHandler
{
void HandleRequest();
}
class Handler : IHandler
{
private IDataContext DataContext { get; set; }
public Handler(IDataContext dataContext)
{
DataContext = dataContext;
}
public void HandleRequest()
{
DataContext.Save("From Handler 1");
}
}
class Handler2 : IHandler
{
private IDataContext DataContext { get; set; }
private IHandler NextHandler { get; set; }
public Handler2(IDataContext dataContext, IHandler handler)
{
DataContext = dataContext;
NextHandler = handler;
}
public void HandleRequest()
{
if (NextHandler != null)
NextHandler.HandleRequest();
DataContext.Save("From Handler 2");
}
}
如您所见,两个处理程序都接受一个 IDataContext 实例,我希望它们在它们中都相同。Handler2 也接受一个 IHandler 的实例来传递控制权(它在此处进行演示,但实际上,只有一个会处理请求......)
数据上下文。在构造函数中,我初始化了一个 Guid,并在它的操作过程中输出它,以便我可以查看它的调用是否使用相同的实例:
public interface IDataContext
{
void Save(string fromHandler);
}
class DataContext : IDataContext
{
private readonly Guid _guid;
public DataContext()
{
_guid = Guid.NewGuid();
}
public void Save(string fromHandler)
{
Console.Out.WriteLine("GUI: [{0}] {1}", _guid, fromHandler);
}
}
最后是服务的注册和调用:
private IUnityContainer container;
private void InitializeUnity()
{
container = new UnityContainer();
container.RegisterType<IHandler, Handler2>("Handler2",
new InjectionConstructor(new ResolvedParameter<IDataContext>(), new ResolvedParameter<IHandler>("Handler1")));
container.RegisterType<IHandler, Handler>("Handler1");
container.RegisterType<IDataContext, DataContext>(new PerResolveLifetimeManager());
container.RegisterType<IServiceClass, ServiceClass>("MyClass", new InjectionConstructor(new ResolvedParameter<IHandler>("Handler2")));
}
private void CallService()
{
var service = container.Resolve<ServiceClass>("MyClass");
service.DoService();
// Resolving and calling again to simulate multiple resolves:
service = container.Resolve<ServiceClass>("MyClass");
service.DoService();
}
这是我得到的输出:
GUI: [f2250055-8a5f-4f80-a1b6-bcc5574138cf] From Handler 1
GUI: [f2250055-8a5f-4f80-a1b6-bcc5574138cf] From Handler 2
GUI: [22a5c0a3-3c5c-4683-807d-bf2b43f3cd0a] From Handler 1
GUI: [22a5c0a3-3c5c-4683-807d-bf2b43f3cd0a] From Handler 2
希望这堵文字墙回答了您的问题...如果不是很抱歉,它确实激发了我需要实施的解决方案...