Autofac Dependencies Per Area

江枫思渺然 提交于 2019-12-07 20:16:28

Using named services is probably your best option. So you'd do something like:

builder
    .RegisterType<ViewDataFactory>()
    .Named<IViewDataFactory>("Area1");    

builder
    .RegisterType<DifferentViewDataFactory>()
    .As<IViewDataFactory>("Area2");

And then if you want to avoid having to then manually register your controllers. You could use this code that I just cobbled together and haven't tested:

Put this attribute somewhere globally accessible:

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class ServiceNamedAttribute : Attribute
{
    private readonly string _key;

    public ServiceNamedAttribute(string key)
    {
        _key = key;
    }

    public string Key { get { return _key; } }
}

Add this module to your Autofac config:

public class ServiceNamedModule : Module
{
    protected override void AttachToComponentRegistration(
        IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Preparing +=
            (sender, args) =>
            {
                if (!(args.Component.Activator is ReflectionActivator))
                    return;

                var namedParameter = new ResolvedParameter(
                    (p, c) => GetCustomAttribute<ServiceNamedAttribute>(p) != null,
                    (p, c) => c.ResolveNamed(GetCustomAttribute<ServiceNamedAttribute>(p).Name, p.ParameterType));

                args.Parameters = args.Parameters.Union(new[] { namedParameter });
            };
    }

    private static T GetCustomAttribute<T>(ParameterInfo parameter) where T : Attribute
    {
        return parameter.GetCustomAttributes(typeof(T), false).Cast<T>().SingleOrDefault();
    }
}

And then you can still auto-register your controllers by decorating the constructor like so:

public class Controller1
{
    public Controller1(ServiceNamed["Area1"] IViewDataFactory factory)
    { ... }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!