0

LogUtil构造函数如下所示:配置UnityContainer参数化的构造函数InjectionConstructor

public LogUtil(object classType) 
    { 

     .... 
    } 

我下面的代码工作正常..

var container = new UnityContainer(); 
container.RegisterType<ILogUtility, LogUtil>(new InjectionConstructor(this.GetType())); 
Logger logger = container.Resolve<Logger>(); 

我有在配置文件中配置构造设置问题。 我配置了容器登记如下:

<container> 
    <register type="ILogUtility, Framework" 
       mapTo="LogUtil, Log4Net"> 

     <constructor> 
      <param name="classType" type="object"> 
      </param> 
     </constructor> 

    </register> 
    </container> 

似乎有在上述结构的构造设置的问题。我无法正确传递“类型”信息。它作为“System.Object”而不是实际的类类型传递。我如何修复上述构造函数配置?

+1

这只是一个猜测,我假设你需要传递类型的名称而不是对象。所以这行''需要改成像'。 ' – oleksii 2012-04-12 18:57:10

回答

1

个人而言,我不会使用构造函数注入。我会做更多的事情是这样的:

public static class Log 
{ 
    private static readonly object SyncLock = new object(); 
    private static ILogFactory _loggerFactory; 

    private static void EnsureFactory() 
    { 
     if (_loggerFactory == null) 
     { 
      lock (SyncLock) 
      { 
       if (_loggerFactory == null) 
       { 
        _loggerFactory = ServiceLocator.Get<ILogFactory>(); 
       } 
      } 
     } 
    } 

    public static ILogHandler For(object itemThatRequiresLogging) 
    { 
     if (itemThatRequiresLoggingServices == null) 
      throw new ArgumentNullException("itemThatRequiresLogging"); 

     return For(itemThatRequiresLoggingServices.GetType()); 
    } 

    public static ILogHandler For(Type type) 
    { 
     if (type == null) 
      throw new ArgumentNullException("type"); 

     EnsureFactory(); 

     return _loggerFactory.CreateFor(type); 
    } 

    public static ILogHandler For<T>() 
    { 
     return For(typeof(T)); 
    } 
} 

它将被用来像:

Log.For(this).Debug("Some Stuff to log.")); //Debug is defined in ILogHandler. 

类型是通过方法调用,而不是传入构造英寸

1

我不相信你可以通过配置来做到这一点。这更多的是静态设置,并且您需要运行时反射。不过,您的LogUtil中的对象应该可以转换回其父类型。有一件事你可以尝试创建一个ILoggableObject接口,你可以设置参数。也就是说,如果您正在寻找可用于所有控件的方法/属性