Chr*_*ris 10 structuremap inversion-of-control
我有以下界面:
public interface ILogger
{
void Debug(string message, params object[] values);
void Info(string message, params object[] values);
void Warn(string message, params object[] values);
void Error(string message, params object[] values);
void Fatal(string message, params object[] values);
}
Run Code Online (Sandbox Code Playgroud)
以及以下实施:
public class Log4netLogger : ILogger
{
private ILog _log;
public Log4netLogger(Type type)
{
_log = LogManager.GetLogger(type);
}
public void Debug(string message, params object[] values)
{
_log.DebugFormat(message, values);
}
// other logging methods here...
}
Run Code Online (Sandbox Code Playgroud)
我的想法是使用structuremap使用执行日志记录的类的Type来实例化Log4netLogger类.但是,我不能为我的生活弄清楚如何将调用类的类型传递给structuremap,以便它可以传递给日志记录实现的构造函数.关于如何做到这一点(或更好的方式)的任何建议都将是最受欢迎的.
Kev*_*evM 25
我们在log4net周围使用类似的ILogger包装器,通常使用构造函数注入.我们使用拦截器作为负责创建Logger的工厂方法.这是我们典型的日志记录设置注册表.
public class CommonsRegistry : Registry
{
public CommonsRegistry()
{
For<ILogger>()
.AlwaysUnique()
.TheDefault.Is.ConstructedBy(s =>
{
if (s.ParentType == null)
return new Log4NetLogger(s.BuildStack.Current.ConcreteType);
return new Log4NetLogger(s.ParentType);
});
var applicationPath = Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location);
var configFile = new FileInfo(Path.Combine(applicationPath, "log4net.config"));
XmlConfigurator.ConfigureAndWatch(configFile);
}
}
Run Code Online (Sandbox Code Playgroud)
当对具体类型存在依赖性时,父类型空检查是必需的.
其余的是可选的log4net设置.
我喜欢这个设置的一件事是能够使用空记录器进行单元测试.
如果类型参数是特定于上下文的,我认为这不会像所示的那样工作。如果您需要在构造函数中传递特定于上下文的内容,则可能必须创建一个返回 ILogger 实例的工厂接口和实现:
public interface ILoggerFactory
{
ILogger Create(Type type);
}
public class LoggerFactory : ILoggerFactory
{
public ILogger Create(Type type)
{
return new Log4netLogger(type);
}
}
Run Code Online (Sandbox Code Playgroud)
可能可以引导 StructureMap 根据类型提供您想要的实例,但这假设您事先知道的类型数量有限。