Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am building an API using Web API and integrating dependency injection using Autofac. I have a requirement whereby the controller should use different repositories based on a url parameter. So for example, one repository has business rules for one client system and a second could have a different set of rules.

I have this interface:

C#
public interface IRepository
{
   void Add();
}


And these two implementations:

C#
 public class RepositoryOne : IRepository
{
   public void Add()
   {
        // rules for repo one
   }
}

public class RepositoryTwo : IRepository
{
   public void Add()
   {
       // rules for repo one
   }
}


Finally, this is my controller:

C#
public class HomeController : ApiController
{
     IRepository repository;

     public HomeController(IRepository repo)
     {
        this.repository = repo;
     }
}


Now as I said, I want to switch the repositroy based on a url parameter. I have managed to get something working using lambda expressions in Autofac but just wanted to know if this was the best approach? The wiki touches on an example like this with CreditCard and alludes to using a delegate factory but I can't then find an example of how to code this.

Here is my regsitration code:

C#
builder.RegisterType<RepositoryOne>();
builder.RegisterType<RepositoryTwo>();
builder.Register<IRepository>(c =>
    {
        var repositoryString = HttpContext.Current.Request.QueryString["repo"];
        var repository = string.IsNullOrEmpty(repositoryString) ? 0 : int.Parse(repositoryString);
        switch (repository)
        {
             case 2:
                 return c.Resolve<RepositoryTwo>();
             case 1:
             default:
                 return c.Resolve<RepositoryOne>();
        }
    });
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900