在工作开发中很多地方都会使用到接口模式开发,这里就会用到依赖注入,.NetCore目前是自带的 ,在 Startup.cs中的 ConfigureServices方法中增加 本篇文章仅支持 3.0版本以下core

 1    public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMemoryCache();
 4             services.AddMvc().AddWebApiConventions();
 5             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
 6             services.Configure<ApiBehaviorOptions>(options =>
 7             {
 8                 options.SuppressConsumesConstraintForFormFileParameters = true;
 9                 options.SuppressInferBindingSourcesForParameters = true;
10                 options.SuppressModelStateInvalidFilter = true;
11             });
12             services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new DefaultContractResolver(); });//返回值小写处理
13             services.AddMvc(option => { option.Filters.Add(typeof(SecurityAuthorizeAttribute)); });//添加过滤器
14             services.AddMvc(option => { option.Filters.Add(typeof(GlobalHandlerErrorAttribute)); });//添加过滤器
15             services.AddSingleton<CacheHelper>();
16             services.AddSingleton<IQRCode, RaffQRCode>();
17             services.AddHttpContextAccessor();
18             services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
19         }

这样明显不够方便 Autofac就解决了这一问题,那么下面就看看Autofac在.NetCore中是如何使用的:

     1、首先建立简单的一个基于接口模式的项目.NteCore Mvc模式 引用  Autofac.Extensions.DependencyInjection的引用

     

 

    2、在 IRepository、IServices、Repository、Services中增加相关代码 所有接口继承自IDependency

   //IRepository
 public interface IBaseRepository<T> : IDependency where T : BaseEntity
    {

        string GetUserName();
    }

//Repository
  public class BaseRepository<T> : IBaseRepository<T> ,IDependency where T : BaseEntity
    {
        public string GetUserName()
        {
            return "just0ne";
        }
    }
//IServices
  public interface IBaseServices<T> : IDependency where T : BaseEntity
    {

        string GetUserName();
    }
//Services
 public class BaseServices<T> : IBaseServices<T> , IDependency where T : BaseEntity
    {
        public readonly IBaseRepository<T> _baseRepository;

        public BaseServices(IBaseRepository<T> baseRepository)
        {
            _baseRepository = baseRepository;
        }

        /// <summary>
        /// 获取一个用户名
        /// </summary>
        /// <returns></returns>
        public string GetUserName()
        {
            return _baseRepository.GetUserName();
        }
    }

 

    3、Aufofac的加入,这边需要在项目启动Startup中调整 ConfigureServices方法。具体如下

    

 public IServiceProvider ConfigureServices(IServiceCollection services) 
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc();
            var builder = new ContainerBuilder();//实例化 AutoFac  容器   
            var assemblys = new List<Assembly>();//Service是继承接口的实现方法类库名称
            string assemblysStr = "IRepository^IServices^Repository^Services"; //程序集名称
            foreach (var item in assemblysStr.Split("^"))
            {
                assemblys.Add(Assembly.Load(item));
            }
            var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
            builder.RegisterAssemblyTypes(assemblys.ToArray())
           .Where(m => baseType.IsAssignableFrom(m) && m != baseType)
           .AsImplementedInterfaces().InstancePerLifetimeScope();
            builder.Populate(services);
            return new AutofacServiceProvider(builder.Build());//将系统自带的修改为Atuofac的 重新返回

        }

           控制器层的调用

   

 

 调用结果:

             

 

           ok 到此完美结束!

 posted on 2019-09-25 21:41  just0ne  阅读(450)  评论(0编辑  收藏  举报