Using an IOC container for several types of concrete

I want to implement IOC in my application, but I'm confused, in my application I have several specific classes that implement the interface. Consider this scenario: -

I have an ICommand Inteface and the following specific types that implement this interface: -

  • Addaddress
  • Addcontact
  • RemoveAddress
  • Removecontact

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

So in the GUI layer I will write

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

In the command box

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

Then, finally, we pass listOfCommands to the service level.

, IOC, . , StructureMap.

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

IOC ?

+3
3

, .. IoC:

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

, , , , IoC. , - .

, , IoC:

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

, , .

, : http://devlicious.com/blogs/krzysztof_kozmic/archive/2010/03/11/advanced-castle-windsor-generic-typed-factories-auto-release-and-more.aspx - , IoC , .

+3

Mark, StructureMap :

ObjectFactory.Initialize(x =>
{
   x.For<ISomeInterface>().Add<SomeImplementation>().Named("SomeName");
}

:

ObjectFactory.Initialize(x =>
{
  x.For<ISomeInterface>().Add<DefaultImplementation>();       
  x.For<ISomeInterface>().Add<SomeImplementation>().Named("SomeName");
}

ObjectFactory.GetInstance<ISomeInterface>();, (, Use Add) - , .

, :

ObjectFactory.Initialize(x =>
{
   // names are arbitrary
   x.For<ICommand>().Add<AddAddress>().Named("AddAddress");
   x.For<ICommand>().Add<RemoveContact>().Named("RemoveContact");
}

:

ObjectFactory.GetNamedInstance<ICommand>("AddAddress");
ObjectFactory.GetNamedInstance<ICommand>("RemoveContact");

, .

+1

IOC " " , ICommand, . StructureMap :

ObjectFactory.GetNamedInstance<ICommand>("AddAddress");

, , StructureMap.

0

Source: https://habr.com/ru/post/1776088/


All Articles