views:

75

answers:

2

Hi,

I have a simple function, just want an idea of how I would convert my coding style to IOC.

public User GetUserByID(int userID)
{
   DataProvider dp = new DataProvider();

   return dp.GetUserByID(userID);
}

my dataprovider is simple ADO.net, it opens a connection, calls the sproc and returns the User object.

A: 

Instead of creating an instance of your DataProvider explicitly in your method, pass it in as an argument to the method. Outside of your method, you could create a factory class to create instances of your DataProvider or use an IOC container like Unity.

pmarflee
+1  A: 

This is how typically you would do it using IoC:

public interface IDataProvider
{
   User GetUserByID(int userID);
}

...

class Client
{
   // Client gets the IDataProvider as a mandatory constructor parameter
   public Client (IDataProvider dataProvider)
   {
      this.dataProvider = dataProvider;
   }

   public User GetUserByID(int userID)
   {
      return dataProvider.GetUserById (userID);
   }

   private IDataProvider dataProvider;
}

...

void Main()
{
   // create IoC container of your choice...
   IoCContainer container = new IoCContainer();
   // ... and then configure it (from a config. file or programmatically)
   container.Configure ();

   // create the Client instance using the container
   // note that the container takes care of creating appropriate IDataProvider 
   // for you
   Client client = container.GetService<Client>();
   User user = client.GetUserByID ("john doe");
}

The only problem with your example is that your client class' method doesn't really add any value to the code - it simply forwards the call to the data provider.

Igor Brejc
+1 on the sample. As for your comment, it might be valuable if it provides abstraction of some sort. It's hard to judge without greater context.
Krzysztof Koźmic