Configuring an Autofac delegate factory that's defined on an abstract class

前端 未结 1 1925
清酒与你
清酒与你 2020-12-16 07:17

I\'m working on a C# project. I\'m trying to get rid of a Factory class that has a large switch statement.

I want to configure Autofac to be able to con

相关标签:
1条回答
  • 2020-12-16 07:45

    What you're looking for is the IIndex<,> Relationship Type.

    If you register your sub-classes with .Keyed<>(...) you can key a registration to a value (object).

    For example:

    builder.RegisterType<SprocketWidget>()
       .Keyed<Widget>(WidgetType.Sproket)
       .InstancePerDependency();
    
    builder.RegisterType<WhizbangWidget>()
       .Keyed<Widget>(WidgetType.Whizbang)
       .InstancePerDependency();
    

    Then you only require a dependency of IIndex<WidgetType,Widget> to mimic factory behaviour.

    public class SomethingThatUsesWidgets
    {    
        private readonly IIndex<WidgetType,Widget> _widgetFactory;
        public SomethingThatUsesWidgets(IIndex<WidgetType,Widget> widgetFactory)
        {
            if (widgetFactory == null) throw ArgumentNullException("widgetFactory");
            _widgetFactory = widgetFactory;
        }
    
        public void DoSomething()
        {
            // Simple usage:
            Widget widget = widgetFactory[WidgetType.Whizbang];
    
            // Safe Usage:
            Widget widget2 = null;
            if(widgetFactory.TryGetValue(WidgetType.Sprocket, out widget2))
            {
                // do stuff
            }
        }
    }
    

    That's using Dependency Injection approach, if you just want to resolve the factory:

    var factory = Container.Resolve<IIndex<WidgetType,Widget>>();
    
    0 讨论(0)
提交回复
热议问题