0
votes

I am developing a .NET MVC 5 Application with Entity Framework 6. I have already create my database.Then I made a simple ViewModel and use it in the HomeController.But when i try to map the ViewModel with the Database model in the controller I get this Error:

Error activating IConfigurationProvider No matching bindings are available, and the type is not self-bindable. Activation path: 3) Injection of dependency IConfigurationProvider into parameter configurationProvider of constructor of type Mapper 2) Injection of dependency IMapper into parameter mapper of constructor of type HomeController 1) Request for HomeController

Suggestions: 1) Ensure that you have defined a binding for IConfigurationProvider. 2) If the binding was defined in a module, ensure that the module has been loaded into the kernel. 3) Ensure you have not accidentally created more than one kernel. 4) If you are using constructor arguments, ensure that the parameter name matches the constructors parameter name. 5) If you are using automatic module loading, ensure the search path and filters are correct.

This is my HomeController:

public ActionResult Index()
    {
        var ads = this.adService
            .GetAll()
            .ToList()
            .Select(x => this.mapper.Map<AdViewModel>(x));


        var viewModel = new MainViewModel()
        {
            Ads = ads,
        };

        return View(viewModel);

        //return View();
    }

This is my AutoMapperConfiguration:

public class AutoMapperConfig
{
    public static IMapperConfigurationExpression Configuration { get; private set; }

    public void Execute(Assembly assembly)
    {
        Mapper.Initialize(
            cfg =>
            {
                var types = assembly.GetExportedTypes();
                LoadStandardMappings(types, cfg);
                LoadCustomMappings(types, cfg);
                Configuration = cfg;
            });
    }

    private static void LoadStandardMappings(IEnumerable<Type> types, IMapperConfigurationExpression mapperConfiguration)
    {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select new
                    {
                        Source = i.GetGenericArguments()[0],
                        Destination = t
                    }).ToArray();

        foreach (var map in maps)
        {
            mapperConfiguration.CreateMap(map.Source, map.Destination);
            mapperConfiguration.CreateMap(map.Destination, map.Source);
        }
    }

    private static void LoadCustomMappings(IEnumerable<Type> types, IMapperConfigurationExpression mapperConfiguration)
    {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();

        foreach (var map in maps)
        {
            map.CreateMappings(mapperConfiguration);
        }
    }
}

}

The NinjectConfig:

 private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind(x =>
        {
            x.FromThisAssembly()
             .SelectAllClasses()
             .BindDefaultInterface();
        });

        kernel.Bind(x =>
        {
            x.FromAssemblyContaining(typeof(IService))
             .SelectAllClasses()
             .BindDefaultInterface();
        });

        kernel.Bind(typeof(IEfRepository<>)).To(typeof(EfRepository<>));
        kernel.Bind(typeof(DbContext), typeof(MsSqlDbContext)).To<MsSqlDbContext>().InRequestScope();
        kernel.Bind<ISaveContext>().To<SaveContext>();
        kernel.Bind<IMapper>().To<Mapper>();

    }

And the Global.asax:

 protected void Application_Start()
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MsSqlDbContext, Configuration>());

        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        var mapper = new AutoMapperConfig();
        mapper.Execute(Assembly.GetExecutingAssembly());
    }

I am looking forward to see an idea for solving this error,and how to inject this IConfigurationProvider?

1

1 Answers

0
votes

Instead of trying to resolve the IConfigurationProvider dependency, I could suggest the approach to map IMapper to an already initialized instance of Mapper. The automapper initialization code will now be executed at Ninject config time rather than in Global.asax.

The changes I would suggest are as follows:

AutoMapperConfig.cs:

public static class AutoMapperConfig
{
    public static IMapperConfigurationExpression Configuration { get; private set; }
    public static IMapper MapperInstance { get; private set; }

    static AutoMapperConfig()
    {
        Mapper.Initialize(cfg =>
        {
            var types = Assembly.GetExecutingAssembly().GetExportedTypes();
            LoadStandardMappings(types, cfg);
            LoadCustomMappings(types, cfg);
            Configuration = cfg;
        });

        MapperInstance = Mapper.Instance;
    }

    private static void LoadStandardMappings(IEnumerable<Type> types, IMapperConfigurationExpression mapperConfiguration)
    {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMapFrom<>) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select new
                    {
                        Source = i.GetGenericArguments()[0],
                        Destination = t
                    }).ToArray();

        foreach (var map in maps)
        {
            mapperConfiguration.CreateMap(map.Source, map.Destination);
            mapperConfiguration.CreateMap(map.Destination, map.Source);
        }
    }

    private static void LoadCustomMappings(IEnumerable<Type> types, IMapperConfigurationExpression mapperConfiguration)
    {
        var maps = (from t in types
                    from i in t.GetInterfaces()
                    where typeof(IHaveCustomMappings).IsAssignableFrom(t) &&
                          !t.IsAbstract &&
                          !t.IsInterface
                    select (IHaveCustomMappings)Activator.CreateInstance(t)).ToArray();

        foreach (var map in maps)
        {
            map.CreateMappings(mapperConfiguration);
        }
    }
}

NinjectConfig:

private static void RegisterServices(IKernel kernel)
{
    kernel.Bind(x =>
    {
        x.FromThisAssembly()
         .SelectAllClasses()
         .BindDefaultInterface();
    });

    kernel.Bind(x =>
    {
        x.FromAssemblyContaining(typeof(IService))
         .SelectAllClasses()
         .BindDefaultInterface();
    });

    kernel.Bind(typeof(IEfRepository<>)).To(typeof(EfRepository<>));
    kernel.Bind(typeof(DbContext), typeof(MsSqlDbContext)).To<MsSqlDbContext>().InRequestScope();
    kernel.Bind<ISaveContext>().To<SaveContext>();
    kernel.Bind<IMapper>().ToMethod(ctx => AutoMapperConfig.MapperInstance);
}

Global.asax:

protected void Application_Start()
{
    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MsSqlDbContext, Configuration>());

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
 }