我有太多的 DAL 类,我需要为通用存储库注册依赖注入。
类示例:
[CollectionName("RenameMe")]
public class Test{
[BsonId]
public ObjectId ID { get; set; }
[BsonElement("u")]
public Guid UserID { get; set; }
}
泛型类示例:
public class GenericRepository<T, ID> : IGenericRepository<T, ID>
{
public virtual T Save(T pobject)
{
_repository.Save(pobject);
return pobject;
}
}
当我手动注册时,我确实喜欢:
container.Register<IGenericRepository<DAL.Product, Guid>, GenericRepository<DAL.Product, Guid>>();
我如何使用 CollectionName 属性为 DAL 命名空间中的每个类自动执行此操作:
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;
}