ارتقاء به ASP.NET Core 1.0 - قسمت 6 - سرویسها و تزریق وابستگیها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۴/۲۰ ۱۳:۱۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
namespace Core1RtmEmptyTest.Services
{
public interface IMessagesService
{
string GetSiteName();
}
public class MessagesService : IMessagesService
{
public string GetSiteName()
{
return "DNT";
}
}
}
{
"dependencies": {
// same as before
"Core1RtmEmptyTest.Services": "1.0.0-*"
}, public void Configure( IApplicationBuilder app, IHostingEnvironment env, IMessagesService messagesService)
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IMessagesService messagesService)
{
app.Run(async context =>
{
var siteName = messagesService.GetSiteName();
await context.Response.WriteAsync($"Hello {siteName}");
});
} System.InvalidOperationException No service for type 'Core1RtmEmptyTest.Services.IMessagesService' has been registered. at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder) System.Exception Could not resolve a service of type 'Core1RtmEmptyTest.Services.IMessagesService' for the parameter 'messagesService' of method 'Configure' on type 'Core1RtmEmptyTest.Startup'. at Microsoft.AspNetCore.Hosting.Internal.ConfigureBuilder.Invoke(object instance, IApplicationBuilder builder) at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMessagesService, MessagesService>();
}
{
"dependencies": {
// same as before
"StructureMap.Dnx": "0.5.1-rc2-final"
}, public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDirectoryBrowser();
var container = new Container();
container.Configure(config =>
{
config.Scan(_ =>
{
_.AssemblyContainingType<IMessagesService>();
_.WithDefaultConventions();
});
//config.For<IMessagesService>().Use<MessagesService>();
config.Populate(services);
});
container.Populate(services);
return container.GetInstance<IServiceProvider>();
} "frameworks": {
"netcoreapp1.0": {}
}, "frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"portable-net45+win8"
]
}
}, private IServiceProvider IocConfig(IServiceCollection services)
{
var container = new Container();
container.Configure(config =>
{
//config.Populate(services); ---> اضافی است
});
container.Populate(services);
return container.GetInstance<IServiceProvider>();
} services.AddScoped<IOperationScoped, Operation>();
using (var scope = scopeFactory.CreateScope())
{
// ...
} public void Configure(IApplicationBuilder app,
ILoggerFactory loggerFactory,
IServiceScopeFactory scopeFactory)
{
using (var scope = scopeFactory.CreateScope())
{
var initializer = scope.ServiceProvider.GetService<IOperationScoped>();
initializer.SeedAsync().Wait();
}
} using Microsoft.Extensions.DependencyInjection; //... var studentOperations = Request.HttpContext.RequestServices.GetService<IStudentOperations>();
{
"IdentityOptions": {
"Lockout": {
"MaxFailedAccessAttempts": 10,
"DefaultLockoutTimeSpan": "0.00:05:00.0000"
}
}
} public class SiteSettings
{
public Identityoptions IdentityOptions { get; set; }
}
public class Identityoptions
{
public LockoutOptions Lockout { get; set; }
} public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(provider => { return Configuration; });
services.Configure<SiteSettings>(options => Configuration.Bind(options));
var provider = services.BuildServiceProvider();
var siteSettingsOptions = provider.GetService<IOptions<SiteSettings>>();
// now use siteSettingsOptions.Value public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IMessagesService messagesService) public async Task<HttpClient> GetHttpClientAsync()
{
var currentContext = _httpContextAccessor.HttpContext;
// ...
} public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor(); var df = languageService.GetAll().GetAwaiter().GetResult();
<Project Sdk="Microsoft.NET.Sdk.Web">
<ItemGroup>
<ProjectReference Include="..\Core1RtmEmptyTest.Services\Core1RtmEmptyTest.Services.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="StructureMap.Dnx" Version="1.2.0" />
</ItemGroup>
</Project> public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<IEmailService, EmailService>()
.AddScoped(x => new Lazy<IEmailService>(() => x.GetRequiredService<IEmailService>()));
// ...
} public class EmailController : Controller
{
private readonly Lazy<IEmailService> _emailService;
public EmailController(Lazy<IEmailService> emailService)
{
_emailService = emailService;
} namespace FirstProjectServices
{
public interface IMessagesService
{
string GetSiteName();
}
public class MessagesService : IMessagesService
{
public string GetSiteName()
{
return "DNT";
}
}
}
namespace FirstProjectServices
{
public interface IMessagesService2
{
string GetSiteName();
}
public class MessagesService2 : IMessagesService2
{
public string GetSiteName()
{
return "DNT";
}
}
} public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
var collection = new ServiceCollection();
services.Scan(scan => scan
// We start out with all types in the assembly of ITransientService
.FromAssemblyOf<IMessagesService>()
.AddClasses(classes => classes.AssignableTo<MessagesService>())
.AsImplementedInterfaces()
.WithTransientLifetime()
);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMessagesService2 _messagesService)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// app.UseDefaultFiles();
// app.UseStaticFiles();
app.Run(async (context) =>
{
string siteName = _messagesService.GetSiteName();
await context.Response.WriteAsync($"Site Name {siteName}");
});
}
} public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Scan(scan => scan.FromAssemblyOf<IMessagesService>()
.AddClasses()
.AsMatchingInterface() // Registers all <`IClassName`, `ClassName`>
.WithTransientLifetime()
);
که لیست آنها به شرح ذیل است:
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.IHostingEnvironment}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.WebHostBuilderContext}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Configuration.IConfiguration}, ImplementationType = null
Lifetime = Transient, ServiceType = {Microsoft.AspNetCore.Hosting.Builder.IApplicationBuilderFactory}, ImplementationType = {Microsoft.AspNetCore.Hosting.Builder.ApplicationBuilderFactory}
Lifetime = Transient, ServiceType = {Microsoft.AspNetCore.Http.IHttpContextFactory}, ImplementationType = {Microsoft.AspNetCore.Http.HttpContextFactory}
Lifetime = Scoped, ServiceType = {Microsoft.AspNetCore.Http.IMiddlewareFactory}, ImplementationType = {Microsoft.AspNetCore.Http.MiddlewareFactory}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IOptions`1[TOptions]}, ImplementationType = {Microsoft.Extensions.Options.OptionsManager`1[TOptions]}
Lifetime = Scoped, ServiceType = {Microsoft.Extensions.Options.IOptionsSnapshot`1[TOptions]}, ImplementationType = {Microsoft.Extensions.Options.OptionsManager`1[TOptions]}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IOptionsMonitor`1[TOptions]}, ImplementationType = {Microsoft.Extensions.Options.OptionsMonitor`1[TOptions]}
Lifetime = Transient, ServiceType = {Microsoft.Extensions.Options.IOptionsFactory`1[TOptions]}, ImplementationType = {Microsoft.Extensions.Options.OptionsFactory`1[TOptions]}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IOptionsMonitorCache`1[TOptions]}, ImplementationType = {Microsoft.Extensions.Options.OptionsCache`1[TOptions]}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILoggerFactory}, ImplementationType = {Microsoft.Extensions.Logging.LoggerFactory}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILogger`1[TCategoryName]}, ImplementationType = {Microsoft.Extensions.Logging.Logger`1[T]}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IConfigureOptions`1[Microsoft.Extensions.Logging.LoggerFilterOptions]}, ImplementationType = null
Lifetime = Transient, ServiceType = {Microsoft.AspNetCore.Hosting.IStartupFilter}, ImplementationType = {Microsoft.AspNetCore.Hosting.Internal.AutoRequestServicesStartupFilter}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.ObjectPool.ObjectPoolProvider}, ImplementationType = {Microsoft.Extensions.ObjectPool.DefaultObjectPoolProvider}
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal.ITransportFactory}, ImplementationType = {Microsoft.AspNetCore.Server.Kestrel.Transport.Libuv.LibuvTransportFactory}
Lifetime = Transient, ServiceType = {Microsoft.Extensions.Options.IConfigureOptions`1[Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServerOptions]}, ImplementationType = {Microsoft.AspNetCore.Server.Kestrel.Core.Internal.KestrelServerOptionsSetup}
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.Server.IServer}, ImplementationType = {Microsoft.AspNetCore.Server.Kestrel.Core.KestrelServer}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IConfigureOptions`1[Microsoft.Extensions.Logging.LoggerFilterOptions]}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IOptionsChangeTokenSource`1[Microsoft.Extensions.Logging.LoggerFilterOptions]}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILoggerProvider}, ImplementationType = {Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILoggerProvider}, ImplementationType = {Microsoft.Extensions.Logging.Debug.DebugLoggerProvider}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.DependencyInjection.IServiceProviderFactory`1[Microsoft.Extensions.DependencyInjection.IServiceCollection]}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.IStartup}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IConfigureOptions`1[Microsoft.Extensions.Logging.LoggerFilterOptions]}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Options.IOptionsChangeTokenSource`1[Microsoft.Extensions.Logging.LoggerFilterOptions]}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILoggerProvider}, ImplementationType = {Microsoft.Extensions.Logging.Console.ConsoleLoggerProvider}
Lifetime = Singleton, ServiceType = {Microsoft.Extensions.Logging.ILoggerProvider}, ImplementationType = {Microsoft.Extensions.Logging.Debug.DebugLoggerProvider}
Lifetime = Singleton, ServiceType = {System.Diagnostics.DiagnosticListener}, ImplementationType = null
Lifetime = Singleton, ServiceType = {System.Diagnostics.DiagnosticSource}, ImplementationType = null
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.IApplicationLifetime}, ImplementationType = {Microsoft.AspNetCore.Hosting.Internal.ApplicationLifetime}
Lifetime = Singleton, ServiceType = {Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor}, ImplementationType = {Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor} public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; } public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
})
.Build(); Unhandled Exception: System.InvalidOperationException: Cannot resolve scoped service from root provider.
namespace ASPNETCoreIdentitySample
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
// ...
.UseDefaultServiceProvider((context, options) =>
{
options.ValidateScopes = context.HostingEnvironment.IsDevelopment();
})
// ...
host.Run();
}
}
} public interface IMultiple {
string GetName ();
}
public class ImplementationOne : IMultiple {
public string GetName () {
return "Abolfazl Roshanzamir";
}
}
public class ImplementationTwo : IMultiple {
public string GetName () {
return "َAndy Madadian";
}
} services.AddScoped<ImplementationOne> ();
services.AddScoped<ImplementationTwo> ();
services.AddScoped<Func<string, IMultiple>> (serviceProvider => key => {
switch (key) {
case "A":
return serviceProvider.GetService<ImplementationOne> ();
case "B":
return serviceProvider.GetService<ImplementationTwo> ();
default:
throw new KeyNotFoundException (); // or maybe return null, up to you
}
}); private readonly Func<string, IMultiple> _serviceAccessor;
public HomeController (Func<string, IMultiple> serviceAccessor) {
this._serviceAccessor = serviceAccessor;
}
public IActionResult Index () {
var implementOne = this._serviceAccessor ("A").GetName (); // Abolfazl Roshanzamir
var implementTwo = this._serviceAccessor ("B").GetName (); // Andy Madadian
return View ();
} private readonly IEnumerable<IMultiple> _services;
public HomeController (IEnumerable<IMultiple> services)
{
_services = services;
} var serviceA = services.First(o => o.GetType() == typeof(ImplementationOne));
var serviceB = services.First(o => o.Name.Equals("MyClassName")); public class WeatherForecastService
{
private readonly DataService _dataService;
public WeatherForecastService(DataService dataService)
{
_dataService = dataService;
} public class WeatherForecastController : ControllerBase
{
private readonly WeatherForecastService _service;
public WeatherForecastController(WeatherForecastService service)
{
_service = service;
} public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<WeatherForecastService>(); Unhandled exception. System.AggregateException: Some services are not able to be constructed
(Error while validating the service descriptor
'ServiceType: TestApp.WeatherForecastService Lifetime: Scoped ImplementationType:
TestApp.WeatherForecastService': Unable to resolve service for type
'TestApp.DataService' while attempting to activate 'TestApp.WeatherForecastService'.)