Autofac如何实现在抽象类自动注入属性 ,而不在实例类中注入 ,如下简单代码
class Program { static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder(); builder.Register(o => new CClient { Rule = o.Resolve<IValidationRule>() }); builder.RegisterType<CInstence>().As<IValidationRule>(); Console.WriteLine(builder.Build().Resolve<CClient>().Rule.Validate()); //CClient w = new CChilde(); //Console.WriteLine(w.Rule.Validate()); Console.ReadKey(); } } public abstract class CAbstract { public IValidationRule Rule { get; set; } public ValidationResult Test() { return Rule.Validate(); } } public class CInstence : IValidationRule { public ValidationResult Validate() { return new ValidationResult("hehe"); } } public class CClient: CAbstract { }
class Program { static void Main(string[] args) { ContainerBuilder builder = new ContainerBuilder(); builder.Register(o => new CClient { Rule = o.Resolve<IValidationRule>() }); builder.RegisterType<CInstence>().As<IValidationRule>(); Console.WriteLine(builder.Build().Resolve<CClient>().Rule.Validate()); //CClient w = new CChilde(); //Console.WriteLine(w.Rule.Validate()); Console.ReadKey(); } } public abstract class CAbstract { public IValidationRule Rule { get; set; } public ValidationResult Test() { return Rule.Validate(); } } public class CInstence : IValidationRule { public ValidationResult Validate() { return new ValidationResult("hehe"); } } public class CClient: CAbstract { }
我想在CAbstract类中就注入好IValidationRule接口的实现CInstence
希望CClient类不关心也不知道具体是怎么实现 的
唉,文化水平太差,也不知道我表达的对不对,希望有人能理解并帮助解决。刚刚接触Autofac,被搞晕了