[英]How do I map to a parent in the same table with NHiberNate using C# (ClassMapping)
[英]C# NHibernate: How to do constructor injection into classmapping derived class?
我是NHibernate
新手。 我不知何故無法為我的問題找到答案。 所以讓我在這里問。
我怎樣才能將某些東西依賴注入到這樣的類中:
/*
public abstract class ByCodeAutoClassMapping<T> : ClassMapping<T> where T : EntityBase ... etc
*/
using App.Data.Persistence.Infrastructure;
using App.Data.Persistence.Infrastructure.Builders;
using Domain;
using NHibernate.Mapping.ByCode;
namespace Persistence.Auto.Mappings
{
public class EmployeeMapping : ByCodeAutoClassMapping<Employee>
{
protected override void InitCustomMappings(TableMapBuilder<Employee> tableMapping)
{
Schema("test");
}
}
}
有沒有辦法先將持久性類注冊到某個IoC
容器中,然后將這些注冊提供給NHibernate
?
謝謝
您應該能夠按照約定注冊映射類。 就像是:
yourContainer.Register(AllTypes.DerivedFrom(typeof(ByCodeAutoClassMapping<>));
當您需要向 NH 注冊映射類型時,您應該能夠使用您的 IoC 容器來解析它們:
nhMappingTypes = yourContainer.Resolve(typeof(ByCodeAutoMapping<>));
我實現了一個派生自 ModelMapper 的新類,並更改了兩個方法的兩個實現:'AddMappings' 和 'AddMapping' 但使用另一個名稱,在新類型 ModelMappers 的構造函數中接收必要的參數。 這里我的實現,我在 ModelMappings 中的必要參數是 ISesion 類型的對象,但它可以是您需要的任何類型:
public class FenixModelMapper : ModelMapper {
//Here
private readonly ISesion _sesion;
public FenixModelMapper(ISesion sesion)
{
_sesion = sesion;
}
public void AgregarMappings(IEnumerable<Type> types)
{
if (types == null)
{
throw new ArgumentNullException("types");
}
foreach (var type in types.Where(x =>
typeof(IConformistHoldersProvider).IsAssignableFrom(x) && !x.IsGenericTypeDefinition))
{
AgregarMapping(type);
}
}
private void AgregarMapping(Type type)
{
object mappingInstance;
try
{
//Here the code, create instante with Reflection passing my object
mappingInstance = Activator.CreateInstance(type, _sesion);
}
catch (Exception e)
{
throw new MappingException("Unable to instantiate mapping class (see InnerException): " + type, e);
}
var mapping = mappingInstance as IConformistHoldersProvider;
if (mapping == null)
{
throw new ArgumentOutOfRangeException("type",
"The mapping class must be an implementation of IConformistHoldersProvider.");
}
AddMapping(mapping);
}
過去,我通過使用 NHibernate攔截器來做到這一點,但現在也許有更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.