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
You need to enable
.WithAttributeFiltering()
onSystemPreferencesController
andPreferencesController
.Based on the documentation.
in your
ConfigureContainer()
, add these 2 lines at bottomI hope, it can help.
Have a good day.