1. 程式人生 > >.net core從依賴注入容器獲取物件

.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     }