.net core 控制台项目中使用依赖注入和配置文件
之前想要新建一个控制台项目,用来调试.net core Web项目,因为每次启动web项目去测试service层的代码太麻烦了,但是控制台项目又没有依赖注入也没有配置文件,只能自己加载了,以下是步骤及代码
- 首先新建一个控制台项目,以下是主要代码,需要从nuget上下载如下类库
Microsoft.Extensions.Hosting
Microsoft.Extensions.Configuration
Microsoft.Extensions.DependencyInjection
class Program
{
private static IFoo _fooService;
private static IConfiguration _configuration;
static async Task Main(string[] args)
{
using IHost host = CreateHostBuilder(args).Build();
using(var provider = host.Services.CreateScope())
{
_fooService = provider.ServiceProvider.GetService<IFoo>();
_configuration = provider.ServiceProvider.GetService<IConfiguration>();
}
var connectionString = _configuration.GetConnectionString("default");
Console.WriteLine(_fooService.Bar());
SQLTest();
Console.ReadKey();
await host.RunAsync();
}
private static void SQLTest()
{
string connectionStr = _configuration.GetConnectionString("default");
SqlConnection conn = new SqlConnection(connectionStr);
conn.Open();
var connState = conn.State;
Console.WriteLine($"数据库状态:{(connState == System.Data.ConnectionState.Open ? "已打开" : "未打开")}");
conn.Close();
}
static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext,config) =>
{
config.SetBasePath(GetApplicationRoot());
config.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
})
.ConfigureServices(services =>
{
services.AddScoped<IFoo, Foo>();
})
;
static string GetApplicationRoot()
{
//此处获取的是执行文件目录(bin目录),我们配置文件一般是放在项目的根目录下,
//所以此处使用正则匹配一下,如果您有更好的方式,欢迎留言告知
var exePath = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);
Regex appPathMatcher = new Regex(@"(?<!fil)[A-Za-z]:\\+[\S\s]*?(?=\\+bin)");
var appRoot = appPathMatcher.Match(exePath).Value;
return appRoot;
}
}
- appsettings.json 文件
{
"ConnectionStrings": {
"default": "server=.;database=ReportServer;uid=sa;pwd=123456"
}
}
- IFoo.cs 文件
public interface IFoo
{
string Bar();
}
- Foo.cs 文件
public class Foo: IFoo
{
public string Bar()
{
return "Get Success";
}
}
- 最终结果,配置文件正常加载,接口正常注入