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:
public interface IRepository
{
IEnumerable<SomeObject> Get();
}
And then a db implementation:
public class DBRepository : IRepository
{
public IEnumerable<SomeObject> Get()
{
}
}
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:
[DataNeeded]
public class CacheRepository : IRepository
{
private readonly IRepository dataRepo;
public CacheRepository(IRepository dataRepo)
{
this.dataRepo = dataRepo;
}
public IEnumerable<SomeObject> Get()
{
return this.dataRepo.Get();
}
}
Finally, I have a calling controller that will use the cache to get an object:
[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:
kernel.Bind<IRepository>().To<DbRepository>().WhenClassHas<DataNeeded>();
kernel.Bind<IRepository>().To<CacheRepository>().WhenClassHas<CacheNeeded>();
Is there a way to mimic this behaviour in Autofac?