0
votes

I have come up with a Question, that what is the usage of Unity Container or NInject if it is handled only for a single instance of an interface.

Ex: Generally we use like this

 
  

   Public Class IEmailSender
    {
       Public Void SendEmail();
    }
    Public Class SMTP: IEmailSender
    {
        Public Void SendEmail()
        {
             // Send Email Logic using SMTP
        }
    }
    Public Class OtherSender: IEmailSender
    {
        Public Void SendEmail()
        {
             // Send Email Logic for Other Sender
        }
    }
    Public Class Builder
    {
      Public Static IEmailSender CreateBuilder(string senderType)
         {
              if(senderType.Equals("SMTP"))
               {
                   Return New SMTP();
               }            
            ElseIf(senderType.Equals("OTHER"))
              {
                     Return New OtherSender();
              }
         }
    }

In my Screen have two buttons #1. Send from SMTP - Event(EventArgs) #2. Send from Other Sender - Event(EventArgs)

Have the Same Logic in two Methods

   IEmailSender emailSender = Builder.CreateBuilder(button.CommandArgument)
   emailSender.sendEmail();

So, How these different scenarios will be handled with Unity Configuration in Unity Block

or NInject Binder,

Your feedback will be highly appreciatable.

1

1 Answers

0
votes

In Unity, You can use named instances to register and retrieve different implementations of a single interface. First You need to register concrete types to the interface using apriopriate names:

var container = new UnityContainer();
container.RegisterType<IEmailSender, SmtpSender>("SMTP");
container.RegisterType<IEmailSender, OtherSender>("OTHER");

After this you can use it in Your code:

IEmailSender emailSender = container.Resolve<IEmailSender>(button.CommandArgument);
emailSender.SendEmail();