Skip to content

Commit

Permalink
Replace calls to GetService<T> with GetRequiredService<T>
Browse files Browse the repository at this point in the history
Even though GetService<T> still exists, GetRequiredService<T> preserves
the old behavior of throwing for missing services.
  • Loading branch information
halter73 committed Oct 16, 2014
1 parent 54ac14f commit a21ed4b
Show file tree
Hide file tree
Showing 38 changed files with 65 additions and 59 deletions.
2 changes: 1 addition & 1 deletion samples/MvcSample.Web/OverloadController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public bool Accept(ActionConstraintContext context)
});

var valueProviderFactory = context.RouteContext.HttpContext.RequestServices
.GetService<ICompositeValueProviderFactory>();
.GetRequiredService<ICompositeValueProviderFactory>();

var factoryContext = new ValueProviderFactoryContext(
context.RouteContext.HttpContext,
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.AspNet.Mvc.Core/ActionResults/JsonResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private IOutputFormatter SelectFormatter(OutputFormatterContext formatterContext
var defaultFormatters = formatterContext.ActionContext
.HttpContext
.RequestServices
.GetService<IOutputFormattersProvider>()
.GetRequiredService<IOutputFormattersProvider>()
.OutputFormatters;

var formatter = _objectResult.SelectFormatter(formatterContext, defaultFormatters);
Expand All @@ -103,7 +103,7 @@ private IOutputFormatter SelectFormatter(OutputFormatterContext formatterContext
formatter = _defaultFormatter ?? formatterContext.ActionContext
.HttpContext
.RequestServices
.GetService<JsonOutputFormatter>();
.GetRequiredService<JsonOutputFormatter>();
}

return formatter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ private IEnumerable<IOutputFormatter> GetDefaultFormatters(ActionContext context
{
formatters = context.HttpContext
.RequestServices
.GetService<IOutputFormattersProvider>()
.GetRequiredService<IOutputFormattersProvider>()
.OutputFormatters;
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public override void ExecuteResult([NotNull] ActionContext context)
var destinationUrl = Url;
var urlHelper = context.HttpContext
.RequestServices
.GetService<IUrlHelper>();
.GetRequiredService<IUrlHelper>();

// IsLocalUrl is called to handle Urls starting with '~/'.
if (urlHelper.IsLocalUrl(destinationUrl))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public abstract class ViewResultBase : ActionResult

public override async Task ExecuteResultAsync([NotNull] ActionContext context)
{
var viewEngine = ViewEngine ?? context.HttpContext.RequestServices.GetService<ICompositeViewEngine>();
var viewEngine = ViewEngine ?? context.HttpContext.RequestServices.GetRequiredService<ICompositeViewEngine>();

var viewName = ViewName ?? context.ActionDescriptor.Name;
var view = FindViewInternal(viewEngine, context, viewName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ internal AntiForgeryTokenStore([NotNull] AntiForgeryOptions config,

public AntiForgeryToken GetCookieToken(HttpContext httpContext)
{
var contextAccessor = httpContext.RequestServices.GetService<IContextAccessor<AntiForgeryContext>>();
var contextAccessor = httpContext.RequestServices.GetRequiredService<IContextAccessor<AntiForgeryContext>>();
if (contextAccessor.Value != null)
{
return contextAccessor.Value.CookieToken;
Expand Down Expand Up @@ -57,7 +57,7 @@ public void SaveCookieToken(HttpContext httpContext, AntiForgeryToken token)
{
// Add the cookie to the request based context.
// This is useful if the cookie needs to be reloaded in the context of the same request.
var contextAccessor = httpContext.RequestServices.GetService<IContextAccessor<AntiForgeryContext>>();
var contextAccessor = httpContext.RequestServices.GetRequiredService<IContextAccessor<AntiForgeryContext>>();
Contract.Assert(contextAccessor.Value == null, "AntiForgeryContext should be set only once per request.");
contextAccessor.SetValue(new AntiForgeryContext() { CookieToken = token });

Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Core/Controller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public IViewEngine ViewEngine
{
_viewEngine = ActionContext?.
HttpContext?.
RequestServices.GetService<ICompositeViewEngine>();
RequestServices.GetRequiredService<ICompositeViewEngine>();
}

return _viewEngine;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ActionDescriptorsCollection ActionDescriptors
private ActionDescriptorsCollection GetCollection()
{
var actionDescriptorProvider =
_serviceProvider.GetService<INestedProviderManager<ActionDescriptorProviderContext>>();
_serviceProvider.GetRequiredService<INestedProviderManager<ActionDescriptorProviderContext>>();
var actionDescriptorProviderContext = new ActionDescriptorProviderContext();

actionDescriptorProvider.Invoke(actionDescriptorProviderContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ protected virtual IReadOnlyDictionary<Type, Func<ActionContext, object>> CreateV
{
var serviceProvider = context.HttpContext.RequestServices;
return new ViewDataDictionary(
serviceProvider.GetService<IModelMetadataProvider>(),
serviceProvider.GetRequiredService<IModelMetadataProvider>(),
context.ModelState);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ public override async Task OnAuthorizationAsync([NotNull] AuthorizationContext c
}
else
{
var authorizationService = httpContext.RequestServices.GetService<IAuthorizationService>();
var authorizationService = httpContext.RequestServices.GetRequiredService<IAuthorizationService>();

if (authorizationService == null)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public TypeFilterAttribute([NotNull] Type type)

public IFilter CreateInstance([NotNull] IServiceProvider serviceProvider)
{
var activator = serviceProvider.GetService<ITypeActivator>();
var activator = serviceProvider.GetRequiredService<ITypeActivator>();
var obj = activator.CreateInstance(serviceProvider, ImplementationType, Arguments ?? new object[0]);

var filter = obj as IFilter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class ValidateAntiForgeryTokenAttribute : Attribute, IFilterFactory, IOrd

public IFilter CreateInstance(IServiceProvider serviceProvider)
{
var antiForgery = serviceProvider.GetService<AntiForgery>();
var antiForgery = serviceProvider.GetRequiredService<AntiForgery>();
return new ValidateAntiForgeryTokenAuthorizationFilter(antiForgery);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Core/Injector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public static void InjectProperty<TProperty>(

if (property.PropertyType.IsAssignableFrom(typeof(TProperty)))
{
property.SetValue(obj, services.GetService<TProperty>());
property.SetValue(obj, services.GetRequiredService<TProperty>());
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Core/KnownRouteValueConstraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private string[] GetAndCacheAllMatchingValues(string routeKey, HttpContext httpC
private static ActionDescriptorsCollection GetAndValidateActionDescriptorsCollection(HttpContext httpContext)
{
var provider = httpContext.RequestServices
.GetService<IActionDescriptorsCollectionProvider>();
.GetRequiredService<IActionDescriptorsCollectionProvider>();
var descriptors = provider.ActionDescriptors;

if (descriptors == null)
Expand Down
12 changes: 6 additions & 6 deletions src/Microsoft.AspNet.Mvc.Core/MvcRouteHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public string GetVirtualPath([NotNull] VirtualPathContext context)
{
// The contract of this method is to check that the values coming in from the route are valid;
// that they match an existing action, setting IsBound = true if the values are OK.
var actionSelector = context.Context.RequestServices.GetService<IActionSelector>();
var actionSelector = context.Context.RequestServices.GetRequiredService<IActionSelector>();
context.IsBound = actionSelector.HasValidAction(context);

// We return null here because we're not responsible for generating the url, the route is.
Expand All @@ -47,7 +47,7 @@ public async Task RouteAsync([NotNull] RouteContext context)
EnsureLogger(context.HttpContext);
using (_logger.BeginScope("MvcRouteHandler.RouteAsync"))
{
var actionSelector = services.GetService<IActionSelector>();
var actionSelector = services.GetRequiredService<IActionSelector>();
var actionDescriptor = await actionSelector.SelectAsync(context);

if (actionDescriptor == null)
Expand Down Expand Up @@ -78,13 +78,13 @@ public async Task RouteAsync([NotNull] RouteContext context)

var actionContext = new ActionContext(context.HttpContext, context.RouteData, actionDescriptor);

var optionsAccessor = services.GetService<IOptions<MvcOptions>>();
var optionsAccessor = services.GetRequiredService<IOptions<MvcOptions>>();
actionContext.ModelState.MaxAllowedErrors = optionsAccessor.Options.MaxModelValidationErrors;

var contextAccessor = services.GetService<IContextAccessor<ActionContext>>();
var contextAccessor = services.GetRequiredService<IContextAccessor<ActionContext>>();
using (contextAccessor.SetContextSource(() => actionContext, PreventExchange))
{
var invokerFactory = services.GetService<IActionInvokerFactory>();
var invokerFactory = services.GetRequiredService<IActionInvokerFactory>();
var invoker = invokerFactory.CreateInvoker(actionContext);
if (invoker == null)
{
Expand Down Expand Up @@ -134,7 +134,7 @@ private void EnsureLogger(HttpContext context)
{
if (_logger == null)
{
var factory = context.RequestServices.GetService<ILoggerFactory>();
var factory = context.RequestServices.GetRequiredService<ILoggerFactory>();
_logger = factory.Create<MvcRouteHandler>();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,8 @@ public static string CollectionTemplate(IHtmlHelper html)
var result = new StringBuilder();

var serviceProvider = html.ViewContext.HttpContext.RequestServices;
var metadataProvider = serviceProvider.GetService<IModelMetadataProvider>();
var viewEngine = serviceProvider.GetService<ICompositeViewEngine>();
var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();
var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();

var index = 0;
foreach (var item in collection)
Expand Down Expand Up @@ -217,7 +217,7 @@ public static string ObjectTemplate(IHtmlHelper html)
}

var serviceProvider = html.ViewContext.HttpContext.RequestServices;
var viewEngine = serviceProvider.GetService<ICompositeViewEngine>();
var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();

foreach (var propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,8 @@ public static string CollectionTemplate(IHtmlHelper html)
var result = new StringBuilder();

var serviceProvider = html.ViewContext.HttpContext.RequestServices;
var metadataProvider = serviceProvider.GetService<IModelMetadataProvider>();
var viewEngine = serviceProvider.GetService<ICompositeViewEngine>();
var metadataProvider = serviceProvider.GetRequiredService<IModelMetadataProvider>();
var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();

var index = 0;
foreach (var item in collection)
Expand Down Expand Up @@ -225,7 +225,7 @@ public static string ObjectTemplate(IHtmlHelper html)
}

var serviceProvider = html.ViewContext.HttpContext.RequestServices;
var viewEngine = serviceProvider.GetService<ICompositeViewEngine>();
var viewEngine = serviceProvider.GetRequiredService<ICompositeViewEngine>();

foreach (var propertyMetadata in modelMetadata.Properties.Where(pm => ShouldShow(pm, templateInfo)))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ private IEnumerable<string> GetViewNames()

private static IHtmlHelper MakeHtmlHelper(ViewContext viewContext, ViewDataDictionary viewData)
{
var newHelper = viewContext.HttpContext.RequestServices.GetService<IHtmlHelper>();
var newHelper = viewContext.HttpContext.RequestServices.GetRequiredService<IHtmlHelper>();

var contextable = newHelper as ICanHasViewContext;
if (contextable != null)
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.AspNet.Mvc.Core/Routing/AttributeRouting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static IRouter CreateAttributeMegaRoute([NotNull] IRouter target, [NotNul
{
var actions = GetActionDescriptors(services);

var inlineConstraintResolver = services.GetService<IInlineConstraintResolver>();
var inlineConstraintResolver = services.GetRequiredService<IInlineConstraintResolver>();
var routeInfos = GetRouteInfos(inlineConstraintResolver, actions);

// We're creating one AttributeRouteGenerationEntry per action. This allows us to match the intended
Expand Down Expand Up @@ -79,12 +79,12 @@ public static IRouter CreateAttributeMegaRoute([NotNull] IRouter target, [NotNul
target,
matchingEntries,
generationEntries,
services.GetService<ILoggerFactory>());
services.GetRequiredService<ILoggerFactory>());
}

private static IReadOnlyList<ActionDescriptor> GetActionDescriptors(IServiceProvider services)
{
var actionDescriptorProvider = services.GetService<IActionDescriptorsCollectionProvider>();
var actionDescriptorProvider = services.GetRequiredService<IActionDescriptorsCollectionProvider>();

var actionDescriptorsCollection = actionDescriptorProvider.ActionDescriptors;
return actionDescriptorsCollection.Items;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public async Task InvokeAsync([NotNull] ViewComponentContext context)

private object CreateComponent([NotNull] ViewContext context)
{
var activator = _serviceProvider.GetService<ITypeActivator>();
var activator = _serviceProvider.GetRequiredService<ITypeActivator>();
var component = activator.CreateInstance(_serviceProvider, _componentType.AsType());
_viewComponentActivator.Activate(component, context);
return component;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ public class RazorPreCompiler

public RazorPreCompiler([NotNull] IServiceProvider designTimeServiceProvider) :
this(designTimeServiceProvider,
designTimeServiceProvider.GetService<IMvcRazorHost>(),
designTimeServiceProvider.GetService<IOptions<RazorViewEngineOptions>>())
designTimeServiceProvider.GetRequiredService<IMvcRazorHost>(),
designTimeServiceProvider.GetRequiredService<IOptions<RazorViewEngineOptions>>())
{
}

Expand All @@ -34,7 +34,7 @@ public RazorPreCompiler([NotNull] IServiceProvider designTimeServiceProvider,
_host = host;
_host.EnableInstrumentation = true;

var appEnv = _serviceProvider.GetService<IApplicationEnvironment>();
var appEnv = _serviceProvider.GetRequiredService<IApplicationEnvironment>();
_fileSystem = optionsAccessor.Options.FileSystem;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.AspNet.Mvc.Razor/RazorPage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private ITagHelperActivator TagHelperActivator
{
if (_tagHelperActivator == null)
{
_tagHelperActivator = ViewContext.HttpContext.RequestServices.GetService<ITagHelperActivator>();
_tagHelperActivator = ViewContext.HttpContext.RequestServices.GetRequiredService<ITagHelperActivator>();
}

return _tagHelperActivator;
Expand Down Expand Up @@ -393,7 +393,7 @@ public virtual string Href([NotNull] string contentPath)
{
if (_urlHelper == null)
{
_urlHelper = Context.RequestServices.GetService<IUrlHelper>();
_urlHelper = Context.RequestServices.GetRequiredService<IUrlHelper>();
}

return _urlHelper.Content(contentPath);
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Razor/RazorPageOfT.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public ModelExpression CreateModelExpression<TValue>([NotNull] Expression<Func<T
{
if (_provider == null)
{
_provider = Context.RequestServices.GetService<IModelMetadataProvider>();
_provider = Context.RequestServices.GetRequiredService<IModelMetadataProvider>();
}

var name = ExpressionHelper.GetExpressionText(expression);
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.AspNet.Mvc.Razor/RazorViewEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ private ViewEngineResult CreateFoundResult(ActionContext actionContext,
// and might store state. We'll use the service container to create new instances as we require.

var services = actionContext.HttpContext.RequestServices;
var view = services.GetService<IRazorView>();
var view = services.GetRequiredService<IRazorView>();

view.Contextualize(page, partial);
return ViewEngineResult.Found(viewName, view);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private IRazorCompilationService RazorCompilationService
// it is ok to use the cached service provider because both this, and the
// resolved service are in a lifetime of Scoped.
// We don't want to get it upgront because it will force Roslyn to load.
_razorcompilationService = _serviceProvider.GetService<IRazorCompilationService>();
_razorcompilationService = _serviceProvider.GetRequiredService<IRazorCompilationService>();
}

return _razorcompilationService;
Expand Down
6 changes: 3 additions & 3 deletions src/Microsoft.AspNet.Mvc.WebApiCompatShim/ApiController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -107,10 +107,10 @@ public void Validate<TEntity>(TEntity entity)
/// </param>
public void Validate<TEntity>(TEntity entity, string keyPrefix)
{
var validator = Context.RequestServices.GetService<IBodyModelValidator>();
var metadataProvider = Context.RequestServices.GetService<IModelMetadataProvider>();
var validator = Context.RequestServices.GetRequiredService<IBodyModelValidator>();
var metadataProvider = Context.RequestServices.GetRequiredService<IModelMetadataProvider>();
var modelMetadata = metadataProvider.GetMetadataForType(() => entity, typeof(TEntity));
var validatorProvider = Context.RequestServices.GetService<ICompositeModelValidatorProvider>();
var validatorProvider = Context.RequestServices.GetRequiredService<ICompositeModelValidatorProvider>();
var modelValidationContext = new ModelValidationContext(metadataProvider,
validatorProvider,
ModelState,
Expand Down
Loading

0 comments on commit a21ed4b

Please sign in to comment.