/// <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中使用
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来获取实例
1
|
HttpContext.RequestServices.GetService<ILoginService<ApplicationUser>>(); |