IServiceProvider in ASP.NET Core

后端 未结 7 1824
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 08:02

I starting to learn changes in ASP.NET 5(vNext) and cannot find how to get IServiceProvider, for example in \"Model\"\'s method

public class Entity 
{
     publ         


        
7条回答
  •  再見小時候
    2021-02-02 08:28

    Do not use GetService()

    The difference between GetService and GetRequiredService is related with exception.

    GetService() returns null if a service does not exist. GetRequiredService() will throw exception.

    public static class ServiceProviderServiceExtensions
    {
        public static T GetService(this IServiceProvider provider)
        {
            return (T)provider.GetService(typeof(T));
        }
    
        public static T GetRequiredService(this IServiceProvider provider)
        {
            return (T)provider.GetRequiredService(typeof(T));
        }
    }
    

提交回复
热议问题