Andrzej
Andrzej

Reputation: 858

Autofac and Automapper - Profiles registred but not resolved

I have a ASP.NET Core app that uses Autofac to inject Automapper.

Firstly, I'm trying to register Automapper profiles from Assembly:

builder.RegisterAssemblyTypes(assembly)
    .AssignableTo<Profile>()
    .OnActivated(e => System.Diagnostics.Debug.WriteLine(e.Instance.GetType()))
    .AutoActivate();

I have introduced some debug logs to check whether my profiles are registred. And it works, I see my profiles in debug window.

Than I register Automapper and try to resolve previously registered profiles:

builder.Register(ctx => new MapperConfiguration(cfg =>
    {
        var resolvedProfiles = ctx.Resolve<IEnumerable<Profile>>(); // Length is 0
        foreach(var resolvedProfile in resolvedProfiles)
        {
            cfg.AddProfile(resolvedProfile);
        }
    }).CreateMapper())
    .SingleInstance();

Doesn't work unfortunantely. Autofac doesn't resolve any of the previously registered profiles. Why and how can I fix it?

Upvotes: 1

Views: 541

Answers (1)

Alex Riabov
Alex Riabov

Reputation: 9165

Just add the type to your registration (via .As<Profile>()):

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .AssignableTo<Profile>()
                .As<Profile>()
                .OnActivated(e => System.Diagnostics.Debug.WriteLine(e.Instance.GetType()))
                .AutoActivate();

Upvotes: 2

Related Questions