简体   繁体   中英

Registering a named type with autofac and using the name for string parameter

I have the following registrations (note that I haven't finished this code yey, so it may not even work as expected):

builder.RegisterType<SimpleInMemoryChannel>()
    .Named<IChannel>("ErrorChannel")
    .WithParameter(new NamedParameter("channelName", "ErrorChannel"));
builder.RegisterType<SimpleInMemoryChannel>()
    .Named<IChannel>("RequestCbrInput")
    .WithParameter(new NamedParameter("channelName", "RequestCbrInput"));

// Constructor: public SimpleInMemoryChannel(string channelName)

As you can see, I'm trying to use the name of the registered object for the channelName value. The code is a bit verbose. Is there some way I can have that assignment happen automatically? eg I'd like to just write:

builder.RegisterType<SimpleInMemoryChannel>()
    .Named<IChannel>("ErrorChannel");
builder.RegisterType<SimpleInMemoryChannel>()
    .Named<IChannel>("RequestCbrInput");

and have the channelName set automatically.

There is nothing in the default functionality which would allow this to happen. You will either need to customise your registration, or your resolving using a factory. The simplest solution is the one you mentioned in your comment - add a helper function for registering the channel - that way you can still use the default resolution process.

Having a RegisterChannel method may be the more elegant solution.

By the way, if you can't have such a method you can use a custom module :

public class NamedParameterModule<TServiceType> : Module
{
    private readonly string _parameterName;

    public NamedParameterModule(String parameterName)
    {
        this._parameterName = parameterName;
    }

    protected override void AttachToComponentRegistration(
        IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        KeyedService keyedService = registration.Services
            .OfType<KeyedService>()
            .FirstOrDefault(ks => ks.ServiceType == typeof(TServiceType));

        if (keyedService != null)
        {
            registration.Preparing += (sender, e) =>
            {
                e.Parameters = e.Parameters.Concat(new Parameter[] { 
                    new NamedParameter(this._parameterName, keyedService.ServiceKey)
                });
            };
        }

        base.AttachToComponentRegistration(componentRegistry, registration);
    }
}

And register it using builder.RegisterModule(new NamedParameterModule<IFoo>("channelName"));

This this dotnetfiddle for live example : https://dotnetfiddle.net/MPfMup .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM