Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am looking at moving from Ninject to Autofac but am struggling to translate one of the useful features - constrained binding through attributes.

I currently have this interface:

C#
public interface IRepository
{
     IEnumerable<SomeObject> Get();
}


And then a db implementation:

C#
public class DBRepository : IRepository
{
   public IEnumerable<SomeObject> Get()
   {
        // call the database
   }
}


Finally, I have a cached implementation that will check in cache and if nothing found, call the db repository. This is passed into the constructor:

C#
[DataNeeded]
public class CacheRepository : IRepository
{
    private readonly IRepository dataRepo;

    public CacheRepository(IRepository dataRepo)
    {
        this.dataRepo = dataRepo;
    }

    public IEnumerable<SomeObject> Get()
    {
        // check the cache and if nothing found:
        return this.dataRepo.Get();
    }
}


Finally, I have a calling controller that will use the cache to get an object:

C#
[CacheNeeded]
public class HomeController : ApiController
{
    private readonly IRepository cacheRepo;
    
    public CacheRepository(IRepository cacheRepo)
    {
        this.cacheRepo= cacheRepo;
    }

    public IEnumerable<SomeObject> Get()
    {
       return this.cacheRepo.Get();
    }
}


As you can see, i have reused the interface to add a cache layer over the data repository and this pattern works quite neatly. I have then used some custom attributes to tell Ninject that I require a certain type of IRepository. This is configured as follows:

C#
kernel.Bind<IRepository>().To<DbRepository>().WhenClassHas<DataNeeded>();
kernel.Bind<IRepository>().To<CacheRepository>().WhenClassHas<CacheNeeded>();


Is there a way to mimic this behaviour in Autofac?
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