ایدهی ثبت خودکار سرویسها، به همراه تنظیمات؛ بدون نوشتن هیچ کدی در ConfigureServices با روش Installer
نویسنده: فرشاد داودی
تاریخ: ۱۳۹۹/۰۱/۰۴ ۱۴:۵۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public void ConfigureServices(IServiceCollection services) {
// DbContext Service
services.AddDbContext<AppDbContext>(options =>
{
options
.UseSqlServer(appSettings.ConnectionStrings.MyConnectionString, sqlServerOptionsBuilder =>
{ sqlServerOptionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(1).TotalSeconds); //Default is 30 seconds
sqlServerOptionsBuilder.EnableRetryOnFailure();
sqlServerOptionsBuilder.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
})
//Tips
.ConfigureWarnings(warning => warning.Throw(RelationalEventId
.QueryPossibleExceptionWithAggregateOperatorWarning));
// Activate EF Second Level Cache
options.AddInterceptors(new SecondLevelCacheInterceptor());
});
// register other services ....
} public static class DbContextServiceCollectionExtensions
{
public static void AddDbContext(this IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
options
.UseSqlServer(appSettings.ConnectionStrings.MyConnectionString, sqlServerOptionsBuilder =>
{
sqlServerOptionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(1).TotalSeconds); //Default is 30 seconds
sqlServerOptionsBuilder.EnableRetryOnFailure();
sqlServerOptionsBuilder.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
})
//Tips
.ConfigureWarnings(warning => warning.Throw(RelationalEventId
.QueryPossibleExceptionWithAggregateOperatorWarning));
// Activate EF Second Level Cache
options.AddInterceptors(new SecondLevelCacheInterceptor());
});
}
} public void ConfigureServices(IServiceCollection services) {
// Add DbContext
services.AddDbContext();
//.... Register other services
} public interface IServiceInstaller
{
void InstallServices(IServiceCollection services, AppSettings appSettings, Assembly startupProjectAssembly);
} public class DbContextInstaller : IServiceInstaller
{
public void InstallServices(IServiceCollection services, AppSettings appSettings, Assembly startupProjectAssembly)
{
services.AddDbContext<AppDbContext>(options =>
{
options
.UseSqlServer(appSettings.ConnectionStrings.MyConnectionString, sqlServerOptionsBuilder =>
{
sqlServerOptionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(1).TotalSeconds); //Default is 30 seconds
sqlServerOptionsBuilder.EnableRetryOnFailure();
sqlServerOptionsBuilder.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
})
//Tips
.ConfigureWarnings(warning => warning.Throw(RelationalEventId
.QueryPossibleExceptionWithAggregateOperatorWarning));
// Activate EF Second Level Cache
options.AddInterceptors(new SecondLevelCacheInterceptor());
});
}
} public static class ServiceInstallerExtensions
{
public static void InstallServicesInAssemblies(this IServiceCollection services, AppSettings appSettings)
{
var startupProjectAssembly = Assembly.GetCallingAssembly();
var assemblies = new[] { startupProjectAssembly, Assembly.GetExecutingAssembly() };
var installers = assemblies.SelectMany(a => a.GetExportedTypes())
.Where(c => c.IsClass && !c.IsAbstract && c.IsPublic && typeof(IServiceInstaller).IsAssignableFrom(c))
.Select(Activator.CreateInstance).Cast<IServiceInstaller>().ToList();
installers.ForEach(i => i.InstallServices(services, appSettings, startupProjectAssembly));
}
} public void ConfigureServices(IServiceCollection services)
{
//* HttpContextAccessor
// services.AddHttpContextAccessor();
//* Controllers
services.AddControllers(options => { options.Filters.Add(new AuthorizeFilter()); })
.AddNewtonsoftJson();
//* Installers
services.InstallServicesInAssemblies(_appSettings);
} public class RegisterServicesUsingAutoRegisterDiInstaller : IServiceInstaller
{
public void InstallServices(IServiceCollection services, AppSettings appSettings, Assembly startupProjectAssembly)
{
var dataAssembly = typeof(SomeRepository).Assembly;
var serviceAssembly = typeof(SomeService).Assembly;
var webFrameworkAssembly = Assembly.GetExecutingAssembly();
var startupAssembly = startupProjectAssembly;
var assembliesToScan = new[] { dataAssembly, serviceAssembly, webFrameworkAssembly, startupAssembly };
#region Generic Type Dependencies
services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
#endregion
#region Scoped Dependency Interface
services.RegisterAssemblyPublicNonGenericClasses(assembliesToScan)
.Where(c => c.GetInterfaces().Contains(typeof(IScopedDependency)))
.AsPublicImplementedInterfaces(ServiceLifetime.Scoped);
#endregion
#region Singleton Dependency Interface
services.RegisterAssemblyPublicNonGenericClasses(assembliesToScan)
.Where(c => c.GetInterfaces().Contains(typeof(ISingletonDependency)))
.AsPublicImplementedInterfaces(ServiceLifetime.Singleton);
#endregion
#region Transient Dependency Interface
services.RegisterAssemblyPublicNonGenericClasses(assembliesToScan)
.Where(c => c.GetInterfaces().Contains(typeof(ITransientDependency)))
.AsPublicImplementedInterfaces(); // Default is Transient
#endregion
#region Register DIs By Name
services.RegisterAssemblyPublicNonGenericClasses(dataAssembly)
.Where(c => c.Name.EndsWith("Repository")
&& !c.GetInterfaces().Contains(typeof(ITransientDependency))
&& !c.GetInterfaces().Contains(typeof(IScopedDependency))
&& !c.GetInterfaces().Contains(typeof(ISingletonDependency)))
.AsPublicImplementedInterfaces(ServiceLifetime.Scoped);
services.RegisterAssemblyPublicNonGenericClasses(serviceAssembly)
.Where(c => c.Name.EndsWith("Service")
&& !c.GetInterfaces().Contains(typeof(ITransientDependency))
&& !c.GetInterfaces().Contains(typeof(IScopedDependency))
&& !c.GetInterfaces().Contains(typeof(ISingletonDependency)))
.AsPublicImplementedInterfaces();
#endregion
}
} sqlServerOptionsBuilder =>{
sqlServerOptionsBuilder.CommandTimeout((int)TimeSpan.FromMinutes(1).TotalSeconds); //Default is 30 seconds
sqlServerOptionsBuilder.EnableRetryOnFailure();
sqlServerOptionsBuilder.MigrationsAssembly(typeof(AppDbContext).Assembly.FullName);
}