C# NHibernate: How to do constructor injection into classmapping derived class?

791 Views Asked by At

I am new with NHibernate. I somehow not able to find answer for my issue. So let me ask here.

How can I dependency inject something into a class like this:

/*
  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");
        }
    }
}

Is there any way to register persistence classes into some IoC container first and then provide these registration to NHibernate ?

Thanks

3

There are 3 best solutions below

1
David Osborne On

You should be able to register the mapping classes by convention. Something like:

yourContainer.Register(AllTypes.DerivedFrom(typeof(ByCodeAutoClassMapping<>));

When you need to register the mapping types with NH, you should then be able to use your IoC container to resolve them:

nhMappingTypes = yourContainer.Resolve(typeof(ByCodeAutoMapping<>));
0
Luis Felipe Diaz Valbuena On

I implement a new class derived of ModelMapper and change two implementations of two methods: 'AddMappings' and 'AddMapping' but with another names, in constructor of new type of ModelMappers receive the necesary parameters. Here my implementation, my necesary parameter in the ModelMappings is a object of ISesion type, but it can be whatever type you need:

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);
}
0
Frederik Gheysels On

In the past, I've done this by using NHibernate interceptors, but maybe there are better approaches right now.