在Console应用程序中,我正在使用Log4Net,在Main方法中我得到了logger对象。现在,我想通过让所有类继承自具有ILog属性并且应该由Property Injection而不是Constructor Injection设置的BaseClass来使这个日志对象在我的所有类中可用。
我正在使用AutoFac IoC容器,如何将我的日志对象注入我的每个类的Log属性?
实现这一目标的最佳/最简单方法是什么?
有没有办法自动解决类型?
以下是我的测试应用程序:
namespace ConsoleApplication1
{
class Program
{
static ILog Log;
static IContainer Container;
static void Main(string[] args)
{
InitializeLogger();
InitializeAutoFac();
// the below works but could it be done automatically (without specifying the name of each class)?
Product.Log = Container.Resolve<ILog>();
// tried below but didn't inject ILog object into the Product
Container.Resolve<Product>();
RunTest();
Console.ReadLine();
}
private static void RunTest()
{
var product = new Product();
product.Do();
}
private static void InitializeAutoFac()
{
var builder = new ContainerBuilder();
builder.Register(c => Log).As<ILog>();
builder.RegisterType<Product>().PropertiesAutowired();
Container = builder.Build();
}
private static void InitializeLogger()
{
log4net.Config.XmlConfigurator.Configure();
Log = LogManager.GetLogger("LoggerName");
}
}
public class Product
{
public static ILog Log { get; set; }
public void Do()
{
// this throws exception because Log is not set
Log.Debug("some Debug");
}
}
}
在我看来,解决方案Ninject created比Autofac中的propertyinjection好得多。因此,我创建了一个自定义属性,这是一个自动注入我的类的postharp方面:
[AutofacResolve]
public IStorageManager StorageManager { get; set; }
我的方面:
[Serializable]
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class AutofacResolveAttribute : LocationInterceptionAspect
{
public override void OnGetValue(LocationInterceptionArgs args)
{
args.ProceedGetValue();
if (!args.Location.LocationType.IsInterface) return;
if ( args.Value != null )
{
args.Value = DependencyResolver.Current.GetService(args.Location.LocationType);
args.ProceedSetValue();
}
}
}
我知道问题的答案已经给出,但我认为这是解决Autofac中自动属性注入的一种非常巧妙的方法。也许它对未来的某些人有用。
builder.Register(c => LogManager.GetLogger("LoggerName"))
.As<ILog>();
builder.RegisterType<CustomClass>()
.PropertiesAutowired();
属性注入适用于Properties而不适用于Fields。在您的课程中,Log是一个字段而不是属性,因此它永远不会被Autofac解析。
我不想使用postharp所以我做了一个快速的解决方案,但它不会自动注入。我是Autofac的新手,应该可以继续使用这个解决方案。
[Serializable]
[AttributeUsage(AttributeTargets.Property)]
public class AutofacResolveAttribute : Attribute
{
}
public class AutofactResolver
{
/// <summary>
/// Injecting objects into properties marked with "AutofacResolve"
/// </summary>
/// <param name="obj">Source object</param>
public static void InjectProperties(object obj)
{
var propertiesToInject = obj.GetType().GetProperties()
.Where(x => x.CustomAttributes.Any(y => y.AttributeType.Name == nameof(AutofacResolveAttribute))).ToList();
foreach (var property in propertiesToInject)
{
var objectToInject = Autofact.SharedContainer.Resolve(property.PropertyType);
property.SetValue(obj, objectToInject, null);
}
}
}
与此通话一起使用:
AutofactResolver.InjectProperties(sourceObject);
使用Property Injection(除了@cuongle答案)。
builder.Register(c => LogManager.GetLogger("LoggerName")).As<ILog>();
builder.RegisterType<Product>()
.WithProperty("Log", LogManager.GetLogger("LoggerName"));
或者你可以在SetLog
类中添加Product
方法:
public class Product
{
public static ILog Log { get; set; }
public SetLog(Log log)
{
this.Log = log;
}
}
这样您就不必再调用LogManager.GetLogger("LoggerName")
两次,而是使用构建器的上下文来解析Log
。
builder.Register(c => LogManager.GetLogger("LoggerName")).As<ILog>();
builder.Register(c =>
var product = new Product();
product.SetLog(c.Resolve<Log>());
return product;
);
使用OnActvated:
一旦组件完全构建,就会引发OnActivated事件。在这里,您可以执行依赖于完全构造的组件的应用程序级任务 - 这些任务很少见。
builder.RegisterType<Product>()
.OnActivated((IActivatedEventArgs<Log> e) =>
{
var product = e.Context.Resolve<Parent>();
e.Instance.SetParent(product);
});
这些选项提供了更多控制,您不必担心@steven评论:
然而,PropertiesAutowired的可怕之处在于它执行了隐式属性注入,这意味着将跳过任何不可解析的依赖项。这使得很容易错过配置错误,并可能导致应用程序在运行时失败