首页 新闻 会员 周边 捐助

Autofac如何实现在抽象类自动注入属性

0
悬赏园豆:50 [已关闭问题] 关闭于 2016-04-02 13:03

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
    {

    }
View Code
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,被搞晕了

随机哥丶的主页 随机哥丶 | 初学一级 | 园豆:159
提问于:2016-04-02 00:42
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册