Templating: Enable DI container scope validation by default for Development environment in all ASP.NET Core 2.0 templates

Created on 22 Apr 2017  路  9Comments  路  Source: dotnet/templating

Update all the ASP.NET Core 2.0 templates to turn on scope validation when in the development environment, e.g.:
``` c#
public class Startup
{
public Startup(IHostingEnvironment env)
{
HostingEnvironment = env;
}

public IHostingEnvironment HostingEnvironment { get; }

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    // Set up container here...

    return services.BuildServiceProvider(validateScopes: HostingEnvironment.IsDevelopment());
}

public void Configure()
{
    ...
}

}
```

@glennc @davidfowl @pakrym @mlorbetske

Most helpful comment

Scope validation makes sure your dependency graph doesn't have mismatched lifetimes (like depending on a scoped service from a singleton service). Read about "Captive dependencies" https://blog.ploeh.dk/2014/06/02/captive-dependency/

Simple injector also has a feature to detect this - https://simpleinjector.readthedocs.io/en/latest/LifestyleMismatches.html

All 9 comments

That's not the beautiful new way to do it

@davidfowl please share the 馃尫
I did wonder if there was a nicer way but couldn't find it just spelunking through IntelliSense.

@davidfowl bump

Worked is moved to https://github.com/aspnet/MetaPackages/pull/61. Please close.

I was looking at the code behind CreateDefaultBuilder and documenting what the defaults are for my colleagues, I'm nice like that, but when it came to validating scopes, I'm not sure.

Can I ask for some background on why its a good idea to validate scopes just for development? Not a loaded question, I literally am ignorant on what this does.

Thanks.

We didn't want the perf hit in production. Since you rarely change registrations at runtime (if ever) you'd catch most things at development time.

And didn't want to throw new unexpected exceptions from DI in production after migration to 2.0

What is scope validation?

Scope validation makes sure your dependency graph doesn't have mismatched lifetimes (like depending on a scoped service from a singleton service). Read about "Captive dependencies" https://blog.ploeh.dk/2014/06/02/captive-dependency/

Simple injector also has a feature to detect this - https://simpleinjector.readthedocs.io/en/latest/LifestyleMismatches.html

Was this page helpful?
0 / 5 - 0 ratings