2

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

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< ISodaService >(); 相反,当我运行程序时,应该自动注入依赖项

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();

        }
    }
4

1 回答 1

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();

        }
    }
于 2013-08-01T16:19:14.430 回答