在要求输入邮箱的文本域,请填写真实的邮件地址。非真实邮件地址,将收不到回复信息。

asp .net core 不使用构造函数获得注入的对象

.net core 清风 1280℃ 2评论

使用asp .net core 2.1使用自带的依赖注入,自带的依赖注入是构造函数注入。有些情况,构造函数注入并不能满足需求,所以需要使用其他方法获取指定实例。

    
public interface IEngine
 {
        /// <summary>
        /// 类型构建
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        object Resolve(Type type);
}
    
public class GetEngine: IEngine
{
        private IServiceProvider _serviceProvider;
        public GetEngine(IServiceProvider serviceProvider)
        {
            this._serviceProvider = serviceProvider;
        }

        /// <summary>
        /// 类型构建
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public object Resolve(Type type)
        {
            return _serviceProvider.GetService(type);
        }
}

public class EnginContext
 {
        private static IEngine _engine;

        [MethodImpl(MethodImplOptions.Synchronized)]
        public static IEngine Initialize(IEngine engine)
        {
            if (_engine == null)
                _engine = engine;
            return _engine;
        }

        public static IEngine Current
        {
            get
            {
                return _engine;
            }
        }
 }

需要在 Startup.csConfigure方法中调用,如下:


EnginContext.Initialize(new GetEngine(app.ApplicationServices));

完整示例如下:


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
 {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            EnginContext.Initialize(new GetEngine(app.ApplicationServices));

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
  }

新增一个类Information进行测试,如下:


    public class Information
    {
        private string Name => "Dot Net Core";
        public string GetName()
        {
            return $"你好!{Name}";
        }
    }

ConfigureServices方法中将新增的类进行注入。


        
        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.AddTransient<Information>();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

通过以下方式进行获取已经注入的对象。


EnginContext.Current.Resolve(typeof(Information));

使用示例如下:


        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";
            var info= EnginContext.Current.Resolve(typeof(Information)) as Information;
            ViewData["Message"] = info.GetName();
            return View();
        }
asp .net core 不使用构造函数获得注入的对象-第0张图片

示例下载

示例



转载请注明:清风亦平凡 » asp .net core 不使用构造函数获得注入的对象

喜欢 (8)or分享 (0)
支付宝扫码打赏 支付宝扫码打赏 微信打赏 微信打赏
头像
发表我的评论
取消评论

CAPTCHA Image
Reload Image
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
(2)个小伙伴在吐槽
  1. 头像
    针对AddScoped的会有问题。
    nbgzc2020-08-25 12:58 回复
    • 头像
      默认情况下在通过AddScoped加入,通过这种形式获取是报错的。.net core默认不允许通过此种访问,有验证作用域范围。如果一定要通过这种形式访问,可以取消作用域验证。在Program.cs文件中使用.UseDefaultServiceProvider(options => { options.ValidateScopes = false; })取消作用域验证。设置后,再使用此种方式也可获取成功,但并不建议使用。
      清风2020-08-25 22:54 回复