0

So if I have:

public class CustomerViewModel
{
    public CustomerViewModel(ICustomer customer)
    {
        this.customer = customer
    }
}

then is there a way to achieve:

ICustomerViewModel customerViewModel = container.Resolve<ICustomerViewModel>(existingCustomer);
sturdytree
  • 849
  • 3
  • 12
  • 26

3 Answers3

3

If you want to build-up an existing instance through property and method injection, you can use the following:

var model = new CustomerViewModel(customer);
model = container.BuildUp(model);

In general I would not recommend using this feature of Unity. Sometimes you need it, but it's usually a warning sign that could be fixed by adjusting the design a bit to work more naturally with IoC as a pattern (not a framework). With more details on how you are using it, the SO community can probably offer some other options...

Mike Valenty
  • 8,941
  • 2
  • 30
  • 32
  • Thanks Michael, although I'm trying to avoid using 'new' in my controller and want my factory to supply new instances using generic methods that use Unity. – sturdytree May 02 '11 at 08:22
1

Since the dependency injection container is designed to provide finished objects, you'll need to use a factory pattern (which is quite common in these cases) to achieve your desired configuration:

public interface ICustomerViewModelFactory {
   public ICustomerViewModel GetModelFor(ICustomer customer);
}

public class CustomerViewModelFactory : ICustomerViewModelFactory {
   public ICustomerViewModel GetModelFor(ICustomer customer) {
      return new CustomerViewModel(customer);
   }
}

// elsewhere...
container.RegisterInstance<ICustomerViewModelFactory>(new CustomerViewModelFactory());

// and finally...
ICustomerViewModelFactory factory = container.Resolve<ICustomerViewModelFactory>();
ICustomerViewModel customerViewModel = factory.GetModelFor(existingCustomer);
Jollymorphic
  • 3,510
  • 16
  • 16
0

Check the 'Can I pass constructor parameters to Unity's Resolve() method?' question (also on Stack Overflow).

Community
  • 1
  • 1
Damian Schenkelman
  • 3,505
  • 1
  • 15
  • 19
  • That's useful, thanks Damian. However, using parameter overrides seems to require using the name of the parameter as a string (brittle design) and using InjectionConstructor requires registering the instance (existingCustomer in my example) in the container. That's impractical when converting many existing domain objects to viewmodels - the conclusion seems to be Unity does not yet allow this. – sturdytree May 02 '11 at 08:26