利用autofac和ServiceLocator实现非mvc项目的带参数注入

1.首先使用nuget安装Autofac.Extras.CommonServiceLocator和autofac

  为什么使用nuget,因为两个包会有很多依赖的包需要下载,为了不必要的麻烦,请使用nuget安装需要的包

2.创建需要的注入的类,接口和接口实现

 public interface ISayAble
    {
        void SayHello();
    }

 

  public class Say:ISayAble
    {
        public void SayHello()
        {
            Console.WriteLine("老子就不是人!");
        }
    }

 

public Person(ISayAble say)
        {
            say.SayHello();
        }

 现在需要将say以参数的形式注入到Person中,再针对ServiceLocator做一些封装

  public static T GetService<T>()
        {
            return ServiceLocator.Current.GetInstance<T>();
        }

        public static void SetService(IContainer container)
        {
            ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));
        }

 使用autofac加载程序,我需要加载的程序集名字是Core.dll,所以

  public static void App_Start()
        {
            var builder = new ContainerBuilder();
            //module注册
            Assembly[] asms = new Assembly[] 
            {
                Assembly.LoadFrom("Core.dll") 
            };
            builder.RegisterAssemblyTypes(asms)
                .Where(t => !t.IsAbstract)
                .PropertiesAutowired()
                .AsImplementedInterfaces();
            IContainer container = builder.Build();
            ServiceResposity.SetService(container);
        }

 当然也可以不用关心dll的名字,直接一股脑全部加载进来,这里不做详解

准备工作做完了,接下来做一些分析,autofac在MVC中如果我没有记错的话,是重写了Controller的调用方法,那这里不是MVC,没有所谓的

调用方法怎么办呢?不要忘了工厂模式,不一定要去直接调用需要注入的方法,我们可以写个工厂来帮我们调用不就好了,

我只是很简单实现了一下这个工厂,代码如下:

 public class Genericresposity<T>
    {
        private ISayAble say = ServiceResposity.GetService<ISayAble>();
        //构造函数
        public void CreateClass()
        {
            Type type = typeof(T);
            ConstructorInfo info = type.GetConstructor(new[] { typeof(ISayAble) });
            info.Invoke(new[] { say });
        }
    }

 当然很乱,我只是很简单写了一下,大概意思就是,我们通过这个resposity去调用我们的Person就可以实现构造函数的注入,那么,其他的一些注入形式是不是都可以这样子做呢,

这个工厂还起到一个作用就是管理我们的实例

调用示例如下:

 public class Genericresposity<T>
    {
        private ISayAble say = ServiceResposity.GetService<ISayAble>();
        //构造函数
        public void CreateClass()
        {
            Type type = typeof(T);
            ConstructorInfo info = type.GetConstructor(new[] { typeof(ISayAble) });
            info.Invoke(new[] { say });
        }
    }

 

转载于:https://www.cnblogs.com/mayuzx/p/8268462.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值