首页 > 技术文章 > Autofac 组件注册与服务解析

tomorrow0 2020-11-25 15:10 原文

组件:组件可以是一个.Net类也可以是一个表达式,同时也可以是一个暴露一个或多个服务的的一段代码,同时组件可以引用其他的依赖。

服务:通常是一个接口(即用户通过接口来使用组件),也可以是.Net类(即组件可以暴露自己给用户作为一个服务),暴露给用户,是用户使用组件的通道。

依赖:一个被组件需要的服务

创建服务和组件

    /// <summary>
    /// 暴露的服务 IOutput
    /// </summary>
    public interface IOutput
    {
        void Write(string content);
    }

    /// <summary>
    /// 组件 ConsoleOutput
    /// </summary>
    public class ConsoleOutput : IOutput
    {
        public void Write(string content)
        {
            Console.WriteLine(content);
        }
    }

组件注册与服务解析

    class Program
    {
        private static IContainer Container { get; set; }

        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            // 注册组件 ConsoleOutput 并且把组件 ConsoleOutput 暴露为服务 IOutput
            builder.RegisterType<ConsoleOutput>().As<IOutput>();
            Container = builder.Build();

            Test();

            Console.Read();
        }

        public static void Test()
        {
            using(var scope= Container.BeginLifetimeScope())
            {
                // outPut为解析服务(依赖) IOutput 后构造的组件 ConsoleOutput 实例
                var outPut = scope.Resolve<IOutput>();
                outPut.Write("Hello World");

                // 出错:The requested service 'AutofacTest.ConsoleOutput' has not been registered
                var outPutSelf = scope.Resolve<ConsoleOutput>();
            }
        }
    }

运行结果:

代码" outPut.Write("Hello World")" 正常运行,输出"Hello World";但是代码" var outPutSelf = scope.Resolve<ConsoleOutput>()"报错 "The requested service 'AutofacTest.ConsoleOutput' has not been registered "

原因:

outPut能够正常解析,因为需要解析的服务 IOutput 已经注册了 组件 ConsoleOutput  所有会构造一个ConsoleOutput  实例给outPut变量;

outPutSelf 需要解析服务 ConsoleOutput 但是目前服务ConsoleOutput 找不到对应的注册组件,导致报错

解决方法:

注册组件ConsoleOutput 并且暴露为服务 ConsoleOutput ,即加上如下代码:

            builder.RegisterType<ConsoleOutput>().AsSelf();

或者下面这行代码:

            builder.RegisterType<ConsoleOutput>();

如下图:

 

推荐阅读