我正在做类似的事情:
private static IServiceProvider serviceProvider;
public Program(IApplicationEnvironment env, IRuntimeEnvironment runtime)
{
var services = new ServiceCollection();
ConfigureServices(services);
serviceProvider = services.BuildServiceProvider();
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
private void ConfigureServices(IServiceCollection services)
{
//Console.WriteLine(Configuration["Data:DefaultConnection:ConnectionString"]);
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<DbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
}
我正在努力使用注入的DbContext来使用该程序。任何的想法?你如何实例化程序并注入所有东西?我不知道在静态Main方法中该怎么做。
是否有相同的内容?
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
喜欢什么?
public static void Main(string[] args) => ConsoleApplication.Run<Program>(args);
答案 0 :(得分:0)
我就这样做了:
public class Startup
{
public static IConfigurationRoot Configuration { get; set; }
public static void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<DbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddSingleton<IMyManager, Manager>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddSingleton<Program, Program>();
}
public static void Main(string[] args)
{
var services = new ServiceCollection();
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
.AddEnvironmentVariables()
.AddUserSecrets();
Configuration = builder.Build();
ConfigureServices(services);
var provider = services.BuildServiceProvider();
CancellationTokenSource ctSource = new CancellationTokenSource();
CancellationToken ct = ctSource.Token;
Task task = Task.Run(async () =>
{
Program program = provider.GetRequiredService<Program>();
await program.Run(ct);
});
try
{
task.Wait();
}
catch (AggregateException e)
{
throw e.InnerException;
}
ctSource.Cancel();
ctSource.Dispose();
}
}
然后程序只是:
class Program
{
private IMyManager _myManager;
public Program(IMyManager myManager)
{
_myManager = myManager;
}
public async Task Run(CancellationToken cancelationToken)
{
while (true)
{
cancelationToken.ThrowIfCancellationRequested();
// My things using _myManager
await Task.Delay(10000, cancelationToken);
}
}
}
我为这个例子删除了一堆东西,所以它可能会在某处崩溃,但你明白了。
答案 1 :(得分:0)
以防万一其他人正在寻找一个小而简单的例子。
这是我最近为一个例子写的一个小型控制台应用程序。它只是在带有单元测试的应用程序中进行DI的小型密码生成器演示。
https://github.com/AnthonySB/PasswordApplication
using System;
using Microsoft.Extensions.DependencyInjection;
using PasswordExercise.Interfaces;
using PasswordExercise.Services;
namespace PasswordExercise
{
class Program
{
static void Main(string[] args)
{
//Dependency injection
var serviceProvider = new ServiceCollection()
.AddSingleton<IPasswordGeneratorService, PasswordGenerator>()
.AddSingleton<IPasswordService, PasswordService>()
.BuildServiceProvider();
//Get the required service
var passwordService = serviceProvider.GetService<IPasswordService>();
//For reading from the console
ConsoleKeyInfo key;
//Display the menu
passwordService.Menu();
do
{
//Read the console key, do not display on the screen
key = Console.ReadKey(true);
switch (key.KeyChar.ToString())
{
case "1":
Console.WriteLine("Simple password: {0}", passwordService.SimplePassword());
break;
case "2":
Console.WriteLine("Moderate password: {0}", passwordService.ModeratePassword());
break;
case "3":
Console.WriteLine("Strong password: {0}", passwordService.StrongPassword());
break;
}
} while (key.Key != ConsoleKey.Escape);
}
}
}
希望这有助于某人。