如何在Autofac中自动解析命名类型?

时间:2015-10-22 14:05:13

标签: c# .net unity-container autofac

在Unity中,我可以注册这样的命名类型

using Microsoft.Practices.Unity;
var container = new UnityContainer();
container.RegisterType<IOutputService, ConsoleOutputService>("Console");
container.RegisterType<IOutputService, MessageBoxOutputService>("MessageBox");
container.RegisterType<ICalculatorReplLoop, CalculatorReplLoop>();
ICalculatorReplLoop loop = container.Resolve<ICalculatorReplLoop>();

并使用此属性

自动解析它
public class CalculatorReplLoop : ICalculatorReplLoop
{
    public CalculatorReplLoop() {}

    [Dependency("MessageBox")]
    public IOutputService OutputService { get; set; }
}

我知道如何在Autofac中注册命名服务

using Autofac;
using Autofac.Core;
var builder = new ContainerBuilder();
builder.RegisterType<ConsoleOutputService>().Named<IOutputService>("Console");
builder.RegisterType<MessageBoxOutputService>().Named<IOutputService>("MessageBox");
builder.RegisterType<CalculatorReplLoop>().As<ICalculatorReplLoop>().SingleInstance();
IContainer container = builder.Build();
ICalculatorReplLoop loop = container.Resolve<ICalculatorReplLoop>();

但如何在CalculatorReplLoop类中解决它?

1 个答案:

答案 0 :(得分:1)

查看此示例代码,这是与两个实现共享合同时自动解决使用autofac的方法之一。

using System;
using Autofac;
using Autofac.Features.Indexed;
namespace AutoFac
    {

        class Program
        {
            static void Main(string[] args)
            {
                var builder = new ContainerBuilder();
                builder.RegisterType<OnlineState>().Keyed<IDeviceState>("online");
                builder.RegisterType<OfflineState>().Keyed<IDeviceState>("offline");

                builder.RegisterType<Modem>().AsImplementedInterfaces();

                var container = builder.Build();

                var r = container.Resolve<IModem>();

                r.print();

            }
        }
    public interface IDeviceState
        {
            string Get();
        }
        public class OnlineState : IDeviceState
        {
            public string Get()
            {
                return "OnlineState";
            }
        }
        public class OfflineState : IDeviceState
        {
            public string Get()
            {
                return "OfflineState";
            }
        }
        public class Modem  : IModem
        {
             readonly IIndex<string, IDeviceState> _states;
             private readonly IDeviceState _deviceState;
             public Modem(IIndex<string, IDeviceState> states)
             {
                 _states = states;
                 _deviceState = _states["online"];
                //_deviceState = _states["offline"];
             }

             public void print()
             {
                 Console.WriteLine(_deviceState.Get());
             }
        }

        public interface IModem
        {
            void print();
        }
    }