我正在尝试通过以下服务中的属性注入,如果我尝试构造函数注入它可以工作,但我想做属性注入,我错过了什么?
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();
}
}