6

I have a .Net Core 2 app and an API controller class which inherits from an abstract base class:

 [Route("api/[controller]")]
 public class MyController : BaseController

On the base controller I have:

public ICommandProcessor CommandProcessor { get; set; }

In my StartUp.cs I have:

builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
                .Where(t => t.IsSubclassOf(typeof(BaseController)))
                .PropertiesAutowired();

However, the CommandProcessor property is always null. I have tried moving it to the derived class and tried registering the type directly as follows:

builder.RegisterType<MyController>().PropertiesAutowired();

and the also the base class:

builder.RegisterType<BaseController>().PropertiesAutowired();

I have tried what is suggested here and here amongst other posts but nothing seems to work, which makes me think that it is an issue in .Net Core 2.

When I inject the ICommandProcessor into the controller constructer it is wired up fine.

It is worth mentioning that I have tried this on other class that is not a controller, registered in the following way in the startup:

builder.RegisterType<DomainEvents>().PropertiesAutowired();

and the property on that is still null also.

EDIT:

I have raised this on the autofac project page on github, and they have advised me to show the full ConfigureServices class, which is below:

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc().AddControllersAsServices();

    // Identity server

    var builder = new ContainerBuilder();

    builder.RegisterModule(new CoreImplementationModule());
    builder.RegisterModule(new PortalCoreImplementationModule());

    builder.Register((context, _) => new DocumentClient(
                    new Uri(Configuration["DocumentDb:Uri"]),
            Configuration["DocumentDb:Key"],
            null,
            new ConsistencyLevel?()))
        .As<IDocumentClient>();

    builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())
        .Where(t => t.IsSubclassOf(typeof(BaseController)))
        .PropertiesAutowired();

    builder.Populate(services);

    builder.RegisterType<DomainEvents>().PropertiesAutowired();

    var container = builder.Build();

    return new AutofacServiceProvider(container);
}
Travis Illig
  • 23,195
  • 2
  • 62
  • 85
Declan McNulty
  • 3,194
  • 6
  • 35
  • 54

0 Answers0