Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using IOC Container for multiple concrete types

I want to implement IOC in my application but i am confused, in my application i have multiple concrete classes which implement an interface. Consider this scenario:-

I have an Inteface ICommand and following concrete types which implement this interface:-

  • AddAddress
  • AddContact
  • RemoveAddress
  • RemoveContact

Basically user performs all this action in UI and then List is passed to the service layer where each command is executed.

So in GUI layer I will write

ICommand command1 = new AddAddress();
ICommand command2 = new RemoveContact();

In command manger

List<ICommand> listOfCommands = List<ICommand>();
listOfCommands.Add(command1);
listOfCommands.Add(command2);

Then finally will pass listOfCommands to service layer.

Now as per my understanding of IOC is only one concrete class is mapped to the interface. And we use this syntax to get our concrete type from StructureMap container.

ICommand command = ObjectFactory.GetInstance<ICommand>();

How should i implement IOC in this scenario?

like image 899
TrueDesign Avatar asked Feb 26 '26 07:02

TrueDesign


1 Answers

In this scenario you're better off making your commands into value objects, i.e. not created by the IoC container:

class AddAddressCommand {
    public AddAddressCommand(string address) {
        Address = address;
    }
    public string Address { get; private set; }
}

When you create a command, you really do want a specific implementation, and you want to parameterise it precisely, both concerns that will work against the services of the IoC container. This will become even more relevant if you decide at some point to serialize the command objects.

Instead, make the service-layer components that execute the commands into IoC-provided components:

class AddAddressHandler : IHandler<AddAddressCommand> {
    public AddAddressHandler(ISomeDependency someDependency) { ... }
    public void Handle(AddAddressCommand command) {
        // Execution logic using dependencies goes here
    }
}

In your case, the component that accepts the list of commands to execute will need to resolve the appropriate handler for each command and dispatch the command object to it.

There's some discussion of how to do this with Windsor here: http://devlicious.com/blogs/krzysztof_kozmic/archive/2010/03/11/advanced-castle-windsor-generic-typed-factories-auto-release-and-more.aspx - the community supporting your IoC container of choice will be able to help you with its configuration.

like image 133
Nicholas Blumhardt Avatar answered Feb 28 '26 04:02

Nicholas Blumhardt