I have too many DAL classes for whitch I need to register dependency injection for generic repository.
Class example:
[CollectionName("RenameMe")]
public class Test{
[BsonId]
public ObjectId ID { get; set; }
[BsonElement("u")]
public Guid UserID { get; set; }
}
Generic class example:
public class GenericRepository<T, ID> : IGenericRepository<T, ID>
{
public virtual T Save(T pobject)
{
_repository.Save(pobject);
return pobject;
}
}
When I register manually, I do like:
container.Register<IGenericRepository<DAL.Product, Guid>, GenericRepository<DAL.Product, Guid>>();
How i can make this automatically for each class in DAL namespace, ofc with CollectionName attribute:
private Container RegisterDAL(Container container)
{
var classes =
from t in Assembly.GetExecutingAssembly().GetTypes()
where t.Namespace != null
where t.IsClass
where t.Namespace.StartsWith("DAL")
where t.CustomAttributes
.Any(i => i.GetType() == typeof(CollectionNameAttribute))
select t;
foreach (var dalClass in classes)
{
var idType = dalClass.CustomAttributes.First(
p => p.AttributeType == typeof(BsonIdAttribute));
// what to fill in in the question marks?
container.Register<IGenericRepository<?, ?>, GenericRepository<?,?>>();
}
return container;
}
You can make an open generic mapping:
// using SimpleInjector.Extensions;
container.RegisterOpenGeneric(
typeof(IGenericRepository<,>),
typeof(GenericRepository<,>));
The RegisterOpenGeneric
extension method is located in the SimpleInjector.Extensions
namespace of the core library.
That will elegantly solve your problem.