views:

300

answers:

1

Hi, in tutorial Validating with a service layer constructor for Product Service looks like this:

ProductService(IValidationDictionary validationDictionary, IProductRepository repository)

and its instance in default controller constructor is created like this:

public ProductController() 
{   
    _service = new ProductService(new ModelStateWrapper(this.ModelState), new roductRepository());

}

If I want to use Unity for DI, second constructor should obviously be used.

public ProductController(IProductService service)
{
    _service = service;
}

But then I do not not know to configure Unity to inject first parameter of ProductServise,because ModelStateWrapper uses ModelState from controller, which is created inside controller and cannot be injected.Is it possible to inject such dependency to ProductService?

A: 

Think.

Here's what you're trying to do:

  • In order to create product controller you need product service
  • in order to create product service you need product controller

you have a vicious circle, that's why you can't do it.

I dunno about implementation Unity, but conceptually, you need to break the circle, like this:

  • create product controller without passing product service to it
  • create product service and pass product controller's model state to it
  • inject product service into product controller via property injection

AFAIK unity does support property injection, but it requires you to put attribute onto the property. If I were you, I'd consider using a less invasive container (pretty much any other is better).

Krzysztof Koźmic
Thanx, now I see I'd a circle dependencies here. I solved it by created a UnityHelper with a generic method like this: public TManager CreateEntityManager<TManager, TInnerInterface>(TInnerInterface innerImplementation) { this.RegisterInstance<TInnerInterface>(innerImplementation); return this.Resolve<TManager>(); }And than I do a resolve like this:IProductService target = unity.CreateEntityManager<IProductService, IValidationDictionary>(modelStateWrapper);Thanx for your help/erik