0
using Microsoft.Practices.Unity;   
..
..
public class ContentsController : BaseController
{
    [Dependency]
    public IContentService contentService { get; set; }

}

I am using Unity to give me an instance of IContentService. However it will only work if I declare this to be public. If I declare private then it _cs is null?

Is the only way I can get this to work by declaring it public ?

Can I declare the IContentService in the controller constructor? If I did that then can someone show me the best syntax and how I would connect this up to a private variable?

Alan2
  • 23,493
  • 79
  • 256
  • 450

2 Answers2

1

There is allready answer here: Unity framework DependencyAttribute only works for public properties? You have to declare variables public to make this attribute work as you expect it to.

Community
  • 1
  • 1
er-v
  • 4,405
  • 3
  • 30
  • 37
1

As for the part about constructor injection:

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>();
Sebastian Weber
  • 6,766
  • 2
  • 30
  • 49