.net core从依赖注入容器获取对象

创建引擎方法:改方法用于在不使用构造注入的情况下从依赖注入容器中获取对象

 /// <summary>
    /// 一个负责创建对象的引擎
    /// </summary>
    public interface IEngine
    {
        T Resolve<T>();
    }
 /// <summary>
    /// 引擎实现类
    /// </summary>
    public class GeneralEngine : IEngine
    {
        private IServiceProvider _provider;
        public GeneralEngine(IServiceProvider provider)
        {
            this._provider = provider;
        }
        /// <summary>
        /// 构建实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>()
        {
            return _provider.GetService<T>();
        }
    }
 /// <summary>
    /// 引擎上下文,在项目初始化过程中实例化一个引擎实例
    /// </summary>
    public class EngineContext
    {
        private static IEngine _engine;
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static IEngine initialize(IEngine engine)
        {
            if (_engine == null)
            {
                _engine = engine;
            }
            return _engine;
        }
        /// <summary>
        /// 当前引擎
        /// </summary>
        public static IEngine Current
        {
            get
            {
                return _engine;
            }
        }
    }

利用上面定义的引擎上下文初始化引擎实例

public void 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();
            services.AddDbContext<GeneralDbContext>(options => options.UseSqlServer(

                    Configuration.GetConnectionString("DefaultConnectionString")
                ));

            // services.AddScoped<ICategoryService, CategoryService>();
            services.AddAssembly("General.Services");
            services.AddScoped(typeof(IRepository<>),typeof(EfRepository<>));
            EngineContext.initialize(new GeneralEngine(services.BuildServiceProvider()));
            
            services.AddAuthentication();
        }

在controller中使用

 1 public class CategoryController : Controller
 2     {
 3         private ICategoryService _categoryService;
 4         //public CategoryController(ICategoryService categoryService)
 5         //{
 6         //    this._categoryService = categoryService;
 7         //}
 8         public IActionResult Index()
 9         {
10             return View();
11         }
12 
13         public IActionResult AddCate()
14         {
15             _categoryService = EngineContext.Current.Resolve<ICategoryService>();
16             _categoryService.Add(new CategoryEntity
17             {
18                 IsMenu = false,
19                 Name = "用户管理4",
20                 IsDisabled = true
21             });
22 
23             return Content("保存成功");
24         }
25     }

猜你喜欢

转载自www.cnblogs.com/Spinoza/p/9984251.html