using Microsoft.Practices.Unity;
..
..
public class ContentsController : BaseController
{
[Dependency]
public IContentService contentService { get; set; }
}
我使用Unity给我一个IContentService的实例。但是,只有我声明这是公开的,它才会起作用。如果我声明私有,那么_cs是否为空?
通过宣布公开,我能通过这种方式实现这一目标吗?
我可以在控制器构造函数中声明IContentService吗?如果我这样做,那么有人可以告诉我最好的语法以及如何将其连接到私有变量?
答案 0 :(得分:1)
这里已有答案: Unity framework DependencyAttribute only works for public properties? 您必须声明变量public才能使此属性按预期工作。
答案 1 :(得分:1)
关于构造函数注入的部分:
public class ContentsController : BaseController
{
private readonly IContentService service;
public ContentsController(IContentService service)
{
if(service == null) throw new ArgumentNullException("service");
this.service = service;
}
}
var container = new UnityContainer();
container.RegisterType<IContentService, MyContentService>();
var controller = container.Resolve<ContentsController>();