skip to Main Content

I am trying to register two instances of the same class but both instances end up share the same parameter values.

I have registered the following in my startup.cs:

using Autofac;
using Autofac.Extensions.DependencyInjection;
 public void ConfigureContainer(ContainerBuilder builder)
    {
// Preferences
        builder.RegisterType<PreferencesRetriever>().As<IPreferencesRetriever>().SingleInstance()
            .WithParameter("collection", _configureMongo(_mongoUrl, MONGODB_PREFERENCES_COLLECTION))
            .Keyed<IPreferencesRetriever>("PreferencesRetriever");
// System Preferences
        builder.RegisterType<PreferencesRetriever>().As<IPreferencesRetriever>().SingleInstance()
            .WithParameter("collection", _configureMongo(_mongoUrl, MONGODB_SYSTEM_PREFERENCES_COLLECTION))
            .Keyed<IPreferencesRetriever>("SystemPreferencesRetriever");
    }

And have set up two controllers below:

using Autofac.Features.AttributeFilters;
public class PreferencesController : ControllerBase
{
    private readonly IPreferencesRetriever _preferencesRetriever;

    private readonly ILogger<PreferencesController> _logger;

    public PreferencesController(
        [KeyFilter("PreferencesRetriever")] IPreferencesRetriever preferencesRetriever,
        ILogger<PreferencesController> logger)
    {
        _preferencesRetriever = preferencesRetriever;
        _logger = logger;
    }
...
}
using Autofac.Features.AttributeFilters;
public class SystemPreferencesController : ControllerBase
{
    private readonly IPreferencesRetriever _preferencesRetriever;

    private readonly ILogger<PreferencesController> _logger;

    public SystemPreferencesController(
        [KeyFilter("SystemPreferencesRetriever")] IPreferencesRetriever preferencesRetriever,
        ILogger<PreferencesController> logger)
    {
        _preferencesRetriever = preferencesRetriever;
        _logger = logger;
    }
...
}

For whatever reason, both controllers end up using the MONGODB_SYSTEM_PREFERENCES_COLLECTION value.

Please let me know if I am missing something here.
I am happy to answer any questions.

2

Answers


  1. You need to enable .WithAttributeFiltering() on SystemPreferencesController and PreferencesController.

    Based on the documentation.

    Login or Signup to reply.
  2. in your ConfigureContainer(), add these 2 lines at bottom

    builder.RegisterType<PreferencesController>().PropertiesAutowired().WithAttributeFiltering();  
    builder.RegisterType<SystemPreferencesController>().PropertiesAutowired().WithAttributeFiltering();
    

    I hope, it can help.
    Have a good day.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search