Search code examples
c#unity-containerenterprise-library

Unity 2.0 Clarification please


Could someone please help me to understand what Unity is and how it's simplifying the coding on example below:

Normal Code

FileLogger myLogger = new FileLogger();
FileLogger myLogger = new FastLogger();

Unity Container Code

// Create container and register types
IUnityContainer myContainer = new UnityContainer();
myContainer.RegisterType<ILogger, FileLogger>();       // default instance
myContainer.RegisterType<ILogger, FastFileLogger>("FastLogger");
ILogger myLogger = myContainer.Resolve<ILogger>();

Also:

  1. What is Container in Unity?
  2. What is Resolve?
  3. What is RegisterType.
  4. What is meant by Type Mapping?
  5. What is IOC

Also what happens if two classes implement the same interface and we do something like below on Unity:

container.RegisterType<IInvoicingService, InvoicingService>()
         .RegisterType<IInvoicingService, ManagerService>();
IInvoicingService service = container.Resolve<IInvoicingService>();
service.GetCount();

Looks like it's going to invoke the getCount method on ManagerService. What should I do to invoke GetCount on InvoicingService and ManagerService?

Yes I have read the documentatation on CodePlex, it just confused me a lot!


Solution

  • For IOC and / or Dependency Injection i can recommend this read:

    http://martinfowler.com/articles/injection.html

    This should help you get a better understanding of what you can achieve by using this patterns. Unity helps you implement this patterns in .NET.

    I will try to answer your bulleted questions with best of my knowledge:

    • Your Container is just that: A container. It is there for you to store your Mappings in.
    • "Resolve" resolves your Interface to a concrete instance of an implementation of that particular interface. However, you only will operate on that interface, therefore making the implementation exchangeable (what is the main reason for doing this whole thing)
    • "RegisterType" typically allows you to register a concrete class for an interface. So you basically say: "This is the interface, and if someone requests this interface to be resolved, return an instance of this concrete class". As you can see you can have default and named Type Mappings.
    • The Type Mapping is the mapping between the Interface and the implementation.