public void ConfigureServices(IServiceCollection services)
{
//services.AddSingleton<>();
//services.AddTransient<IMyService, MyService>();
//services.AddSingleton(typeof(IAdminBLL), typeof(AdminBLLImp));
//业务层注入
Assembly assemblys = Assembly.Load("BLL");
//接口
var typesInterface = assemblys.GetTypes().Where(w => w.Namespace == "BLL.BLL.Interface");
//实现类
var typesImpl= assemblys.GetTypes().Where(w => w.Namespace == "BLL.BLL.Implementation");
foreach (var item in typesInterface)
{
var name = item.Name.Substring(1);
var impl = typesImpl.FirstOrDefault(w => w.Name.Contains(name));
if (impl!=null)
{
services.AddTransient(item, impl);
}
}
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
.NET5版本自动注入参考
Startup.cs
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using WebNetCore5_Img_Storage.BLL;
using WebNetCore5_Img_Storage.Handler;
using WebNetCore5_Img_Storage.IBLL;
using WebNetCore5_Img_Storage.Model.Tool;
namespace WebNetCore5_Img_Storage
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//解决中文输出后被编码了
services.Configure<Microsoft.Extensions.WebEncoders.WebEncoderOptions>(options =>
{
options.TextEncoderSettings = new System.Text.Encodings.Web.TextEncoderSettings(System.Text.Unicode.UnicodeRanges.All);
});
//services.AddControllersWithViews();
//添加全局筛选器:
services.AddControllersWithViews(options =>
{
options.Filters.Add(typeof(CustomExceptionFilter));
})
//自定义格式化json使用Newtonsoft.Json
.AddNewtonsoftJson();
//services.addNew
services.AddRazorPages();
//session配置缓存组件依赖,分布式缓存
//services.AddDistributedMemoryCache();
//会话存活时间,单位(秒)
int sessionTime = 0;
int.TryParse(MyConfigReader.GetConfigValue("session_live_time"), out sessionTime);
if (sessionTime == 0)
{
sessionTime = 7200;
}
services.AddSession(options =>
{
//设置cookie名称
//options.Cookie.Name = ".AspNetCore.Session";
//会话滑动过期时间,距下次访问最小时间,超过则session失效
options.IdleTimeout = TimeSpan.FromSeconds(sessionTime);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
//业务层注入
//services.AddScoped<IImgBLL, ImgBLLImpl>();
string path = AppDomain.CurrentDomain.BaseDirectory;
Assembly bll_impl = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.BLL.dll");
Assembly bll_interface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IBLL.dll");
var typesInterface = bll_interface.GetTypes();
var typesImpl = bll_impl.GetTypes();
foreach (var item in typesInterface)
{
var name = item.Name.Substring(1);
string implBLLImpName = name + "Impl";
var impl = typesImpl.FirstOrDefault(w => w.Name.Equals(implBLLImpName));
if (impl != null)
{
//services.AddTransient(item, impl);
//services.AddSingleton(item, impl);
services.AddScoped(item, impl);
}
}
//数据层注册
Assembly dalAssemblys = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.DAL.dll");
Assembly dalInterface = Assembly.LoadFrom(path + "WebNetCore5_Img_Storage.IDAL.dll");
var dalTypesImpl = dalAssemblys.GetTypes();
var dalTypesInterface = dalInterface.GetTypes();
foreach (var item in dalTypesInterface)
{
var name = item.Name.Substring(1);
string implDalName = name + "Impl";
var impl = dalTypesImpl.FirstOrDefault(w => w.Name.Equals(implDalName));
if (impl != null)
{
//services.AddTransient(item, impl);
services.AddScoped(item, impl);
}
}
// services.AddSingleton<IAuthorizationMiddlewareResultHandler, Handler.LoginFilter>();
//services.AddSingleton<IAuthorizationHandler, LoginFilter>();
services.AddMvcCore();
//ConfigureServices结束
services.AddScoped<Microsoft.AspNetCore.SignalR.IUserIdProvider, GetUserId>();
services.AddSignalR();
//services.AddAuthentication().AddCookie();
//CookieAuthenticationDefaults.AuthenticationScheme
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
//app.UseHttpsRedirection();
app.UseStaticFiles(new StaticFileOptions()
{
//不限制content-type下载
ServeUnknownFileTypes = true,
配置的虚拟路径映射
//RequestPath = "/local",
物理地址
//FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider("D:\\Work\\西南油气田图库系统\\WebNetCore5_Img_Storage\\WebNetCore5_Img_Storage\\bin\\Debug\\net5.0"),
});
app.UseRouting();
//app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
//app.UseResponseCaching();
//app.UseResponseCompression();
//用MVC模式, 针对services的services.AddControllersWithViews();
app.UseEndpoints(endpoints =>
{
//endpoints.MapDefaultControllerRoute();
endpoints.MapRazorPages();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapHub<ChatHub>("/chathub");
});
}
}
}