可以通过Nuget包管理器下载Autofac,添加引用

Program.cs的代码如下:

  class Program
    {
        private static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            //这里通过ContainerBuilder方法RegisterType对NotificationSender进行注册,当注册的类型在相应得到的容器中可以Resolve你的NotificationSender实例。 
            builder.RegisterType<NotificationSender>();

            //通过AS可以让SMSService,EmailService类中通过构造函数依赖注入类型相应的接口。
            builder.RegisterType<SMSService>().As<IMobileService>().InstancePerDependency();
            builder.RegisterType<EmailService>().As<IEmailService>().InstancePerDependency();

            //Build()方法生成一个对应的Container实例,这样,就可以通过Resolve解析到注册的类型实例
            using (var container = builder.Build())
            {
                container.Resolve<IMobileService>().Execute();
                container.Resolve<IEmailService>().Execute();
                Console.WriteLine("-----------------------------------------------------");
                Console.WriteLine("结果同上:");
                var notificationSender = container.Resolve<NotificationSender>();
                notificationSender.SetEmailService = container.Resolve<IEmailService>();//属性注入
                notificationSender.SentNotification();
                Console.ReadKey();
            } 
          

            
        }
    }
EmailService.cs和IEmailService.cs代码:

public interface IEmailService
    {
        void Execute();
    }
  public class EmailService : IEmailService
    {
        public void Execute()
        {
            Console.WriteLine("Email 服务执行...");
        }
    }
IMobileService.cs和SMSService.cs的代码如下:
 public interface IMobileService
    {
        void Execute();
    }
  public class SMSService : IMobileService
    {
        public void Execute()
        {
            Console.WriteLine("SMS 服务执行...");
        }
    }
NotificationSender.cs的代码如下:

 public class NotificationSender
    {
        public IMobileService mobileService;
        public IEmailService emailService;

        //实现构造函数注入
        public NotificationSender(IMobileService mobileService)
        {
            this.mobileService = mobileService;
        }

        //属性注入
        public IEmailService SetEmailService
        {
            set { emailService = value; }
        }

        public void SentNotification()
        {
            mobileService.Execute();
            emailService.Execute();
        }
    }
结果如图:







Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐