Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autofac error: The instance registration can support SingleInstance() sharing only

When I try to register my class with autofac I get the following error: "The instance registration 'GetAllDivisionsCommand' can support SingleInstance() sharing only".

I don't understand why I'm getting this error, but assume it's something to do with the class having static member variables used for caching as that's the only thing that's different about this class. I haven't had any trouble registering any other classes as either SingleInstance or InstancePerDependency.

Essentially, the class is used to retrieve a rarely changing list of divisions from the database, and caches the result. Each time the command is run, it first checks for changes on the database and then re-runs the query if changes are detected; if not, it returns the cached list.

So I am trying to register GetAllDivisionsCommand with Autofac as an IGetAllDivisionsCommand. IGetAllDivisionsCommand itself implements IInjectableCommand, which is just a marker interface, and ICachedListCommand. The concrete command class inherits from the abstract base class CachedListCommand which is where the static member variables live.

Does anyone know what would cause this error message? SingleInstance won't work for me as I can't keep reusing the same session.

Code:

Type commandType = typeof(IInjectedCommand);
        Type aCommandType = typeof(GetAllDivisions);

        var commands =
            from t in aCommandType.Assembly.GetExportedTypes()
            where t.Namespace == aCommandType.Namespace
                  && t.IsClass
                  && !t.IsAbstract
                  && (commandType.IsAssignableFrom(t))
            let iface = t.GetInterfaces().FirstOrDefault(x => "I" + t.Name == x.Name)
            select new { Command = t, Interface = iface };

        foreach (var cmd in commands)
        {
            builder.RegisterInstance(cmd.Command).As(cmd.Interface).InstancePerLifetimeScope();
        }
like image 261
kasey Avatar asked Oct 24 '25 19:10

kasey


1 Answers

RegisterInstace as the name implies is for registering instances not types.

What you need is RegisterType:

foreach (var cmd in commands)
{
    builder.RegisterType(cmd.Command).As(cmd.Interface).InstancePerLifetimeScope();
}

And by the way with the Autofac scanning feature your registration code is roughly equivalent:

builder
    .RegisterAssemblyTypes(aCommandType.Assembly)
    .AssignableTo<IInjectedCommand>()
    .InNamespace(aCommandType.Namespace)
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();
like image 77
nemesv Avatar answered Oct 27 '25 00:10

nemesv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!