相聚一刻

相聚一刻

导航

注入实例获取

Posted on 2020-06-27 15:56  相聚一刻  阅读(123)  评论(0编辑  收藏  举报

/// <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 interface IEngine
{
T Resolve<T>();
}

 

 

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

 

在startup中添加

ServiceProvider serviceProvider = services.BuildServiceProvider();


EngineContext.initialize(new GeneralEngine(serviceProvider));

 

在cntrol中引用

private ISaleListService saleService = EngineContext.Current.Resolve<ISaleListService>(); 

 

 

3.3 View中使用

在View中需要用@inject 再声明一下,起一个别名。
1
2
3
4
5
6
7
8
9
10
@using MilkStone.Services;
@model MilkStone.Models.AccountViewModel.LoginViewModel
@inject ILoginService<ApplicationUser>  loginService
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
  @loginService.GetUserName()
</body>
</html>

  

3.4 通过 HttpContext来获取实例

HttpContext下有一个RequestedService同样可以用来获取实例对象,不过这种方法一般不推荐。同时要注意GetService<>这是个范型方法,默认如果没有添加Microsoft.Extension.DependencyInjection的using,是不用调用这个方法的。
1
HttpContext.RequestServices.GetService<ILoginService<ApplicationUser>>();