使用autofac进行性质注入3.1.1

时间:2013-07-25 15:13:53

标签: c# properties dependency-injection autofac code-injection

我试图通过以下服务注入属性,如果我尝试构造函数注入它的工作但我想做属性注入,我错过了什么?

public class SodaService  
{  
    public ISoda _s;

    //public SodaService(ISoda s)  
    //{  
    //    _s = s;  
    //}  

    public string GetSoda()
    {
        return _s.SodaName;
    }
}

//Soda Class implementing ISoda  

public class Soda : ISoda  
{  
    public string SodaName
    {
        get { return "Default Soda"; }
    }
}

public interface ISoda  
{  
    string SodaName { get; }
}

//Main calling program

class Program  
{  
    static void Main(string[] args)  
    {  
        var container = GetContainer();   
        SodaService s=container.Resolve<SodaService>();    
        Console.Write(s.GetSoda());  
        Console.Read();  
    }  

    private static IContainer GetContainer()
    {
        var builder = new ContainerBuilder();
        builder.RegisterType<Soda>().As<ISoda>();
        builder.RegisterType<SodaService>()
            .PropertiesAutowired();

        var container = builder.Build();
        return container;
    }
}

编辑: 上面的问题已经解决,我还有一个问题......

我怎么能做这样的工作,我不想用 s = container.Resolve&lt; ISodaService&gt;(); 而且当我运行程序时,应该自动注入依赖项

class Program
    { 
        public static ISodaService s { get; set; }
        static void Main(string[] args)
        {
            SetUpContainer();

            //s = container.Resolve<ISodaService>();
            Console.Write(s.GetSoda());
            Console.Read();
        }

        private static void SetUpContainer()
        {
            var builder = new ContainerBuilder();
             builder.RegisterType<Soda>().As<ISoda>();
          builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired();

           builder.Build();

        }
    }

1 个答案:

答案 0 :(得分:1)

你遇到的问题是Main方法是静态的。实例化一类程序并使用非静态类

class Program
    { 
        public ISodaService s { get; set; }
        static void Main(string[] args)
        {
            var resolver=SetUpContainer();
            var instance=resolver.Resolve<Program>();
            instance.Execute(args);
        }

        public void Execute(string[] args)
        {

            Console.Write(s.GetSoda());
            Console.Read();
        }

        private Autofac.IContainer void SetUpContainer()
        {
          var builder = new ContainerBuilder();
          builder.RegisterType<Soda>().As<ISoda>();
          builder.RegisterType<SodaService>().As<ISodaService>().PropertiesAutowired();
          builder.RegisterType<Program>().PropertiesAutowired();
          return builder.Build();

        }
    }