1
votes

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?

1
I know, but will it work when I use Autofac as IoC Container?Andrzej
I'm sure you can replace the default DI engine with Autofac and use the same interface.Lucian Bargaoanu

1 Answers

2
votes

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();