C# 通过简单注入器构造时,将SessionId添加到记录器
使用c#MVC和 我的记录器就是这样创建的C# 通过简单注入器构造时,将SessionId添加到记录器,c#,asp.net-mvc,dependency-injection,simple-injector,C#,Asp.net Mvc,Dependency Injection,Simple Injector,使用c#MVC和 我的记录器就是这样创建的 container.Register<ILogger>(() => new Logger("MVC Logging Startup"), Lifestyle.Scoped); container.Register(()=>newlogger(“MVC日志记录启动”),livelity.Scoped); 这被完美地传递到所有需要它的类中。但是,我需要一种方法来识别发生在用户身上的事件。在我看来,实现这一点最简单的方法是将sessio
container.Register<ILogger>(() => new Logger("MVC Logging Startup"), Lifestyle.Scoped);
container.Register(()=>newlogger(“MVC日志记录启动”),livelity.Scoped);
这被完美地传递到所有需要它的类中。但是,我需要一种方法来识别发生在用户身上的事件。在我看来,实现这一点最简单的方法是将sessionId传递给记录器,这样每次使用记录器的类(无论是控制器、业务类还是数据处理类)都可以跟踪单个会话事件
container.Register<ILogger>(() => new Logger(this.Session.SessionId), Lifestyle.Scoped);
container.Register(()=>newlogger(this.Session.SessionId),lifesture.Scoped);
不会在应用程序启动时工作
HttpContext
为null
。我能看到的唯一方法是在每次调用控制器构造函数时手动将sessionId
设置到记录器中。但这似乎是违反直觉的。因此,我如何将当前的会话ID
(或唯一标识符)传递到我的记录器中。您遇到的问题是由您造成的。这是一种反模式,应加以防止,因为:
它会导致歧义,使组合根复杂化,并承担额外的责任,并且使验证DI配置的正确性变得异常困难
解决办法是:
让运行时数据流过构造的对象图的方法调用
链接文章还描述了问题的解决方案,即提取抽象背后的运行时值。例如:
public interface IUserContext
{
int SessionId { get; }
}
这可以通过以下方式实现:
class HttpSessionUserContext : IUserContext
{
public int SessionId => (int)HttpContext.Current.SessionId;
}
var userContext = new HttpSessionUserContext();
container.Register<ILogger>(() => new Logger("MVC Logging Startup", userContext),
Lifestyle.Scoped);
现在,您可以按以下方式完成注册:
class HttpSessionUserContext : IUserContext
{
public int SessionId => (int)HttpContext.Current.SessionId;
}
var userContext = new HttpSessionUserContext();
container.Register<ILogger>(() => new Logger("MVC Logging Startup", userContext),
Lifestyle.Scoped);
var userContext=newhttpsessionusercontext();
container.Register(()=>newlogger(“MVC日志记录启动”,userContext),
生活方式(范围);
您遇到的问题是由您造成的。这是一种反模式,应加以防止,因为:
它会导致歧义,使组合根复杂化,并承担额外的责任,并且使验证DI配置的正确性变得异常困难
解决办法是:
让运行时数据流过构造的对象图的方法调用
链接文章还描述了问题的解决方案,即提取抽象背后的运行时值。例如:
public interface IUserContext
{
int SessionId { get; }
}
这可以通过以下方式实现:
class HttpSessionUserContext : IUserContext
{
public int SessionId => (int)HttpContext.Current.SessionId;
}
var userContext = new HttpSessionUserContext();
container.Register<ILogger>(() => new Logger("MVC Logging Startup", userContext),
Lifestyle.Scoped);
现在,您可以按以下方式完成注册:
class HttpSessionUserContext : IUserContext
{
public int SessionId => (int)HttpContext.Current.SessionId;
}
var userContext = new HttpSessionUserContext();
container.Register<ILogger>(() => new Logger("MVC Logging Startup", userContext),
Lifestyle.Scoped);
var userContext=newhttpsessionusercontext();
container.Register(()=>newlogger(“MVC日志记录启动”,userContext),
生活方式(范围);
您可以注册一个全局变量,该变量将在执行操作之前执行(OnActionExecuting
),谢谢Stron。我更喜欢另一个答案,因为它与我的解决方案的其余部分的工作方式一致。您可以注册一个全局变量,该变量将在执行操作之前执行(OnActionExecuting
),谢谢Stron。我更喜欢另一个答案,因为它与我的其他解决方案的工作方式一致。