.NET 6 WPF利用Ninject注册服务(DI)代码示例以及同.NET 6 API DI的对比。
目录
1.安装Ninject
2. 创建IService.cs 和实现类
2.1 IDapperHelper.cs
2.2 DapperHelper.cs
3. 创建UtilAndServiceModule.cs,Bind所有Services
4. 创建NInjectBase.cs,Register所有的Services
5. 使用Service
6. Ninject对比.NET 6 API DI
7. DI lifecycle
Transient
Scoped
Singleton
Visual Studio --> 右击Solution--》 Manage NuGet Packages For Solutiuon...
Browser 输入ninject, 目前我本地用的版本是3.3.6。
using System;
using System.Collections.Generic;
using System.Data;
using Microsoft.Data.SqlClient;
public interface IDapperHelper
{
///
/// This function support DynamicParameters
///
///
/// DynamicParameters,like new { PaymentIds = paymentIds.AsTableValuedParameter("dbo.IdTable", new List() { "Id" }) }
///
///
///
int Execute(string sqlCommand, object parameters, int? commandTimeout = null, CommandType commandType = CommandType.Text);
}
using Dapper;
using log4net;
using Microsoft.Data.SqlClient;
using static Dapper.SqlMapper;
using System.Configuration;
public class IDapperHelper : IDapperHelper
{
public int Execute(string sqlCommand, object parameters, int? commandTimeout = null, CommandType commandType = CommandType.Text)
{
using (SqlConnection Connection = GetSqlConnection())
{
try
{
Connection.Open();
int returnValues = Connection.Execute(sqlCommand, parameters, commandTimeout: commandTimeout, commandType: commandType);
Connection.Close();
Connection.Dispose();
return returnValues;
}
catch (Exception e)
{
Log.Error(e);
}
finally
{
Connection.Close();
Connection.Dispose();
}
}
return -1; // Failure.
}
private SqlConnection GetSqlConnection()
{
var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
var connStr = AgencyConfigurationManager.GetDecryptedConnectionString(connectionString);
return new SqlConnection(connStr);
}
}
InSingletonScope: Indicates that only a single instance of the binding should be created, and then should be re-used for all subsequent requests.
InTransientScope: Indicates that instances activated via the binding should not be re-used, nor have their lifecycle managed by Ninject.
InScope: Indicates that instances activated via the binding should be re-used as long as the object returned by the provided callback remains alive (that is, has not been garbage collected).
InThreadScope:Indicates that instances activated via the binding should be re-used within the same thread.
using Ninject.Modules;
public class UtilAndServiceModule : NinjectModule
{
public override void Load()
{
Bind().To().InTransientScope();
Bind().To().InTransientScope();
}
}
using System.Text;
using Ninject;
public class NInjectBase
{
public static IKernel Kernel
{
get
{
lock (new object())
{
if (_kernel == null) LoadKernel();
return _kernel;
}
}
}
private static IKernel _kernel;
private static void LoadKernel()
{
_kernel = new StandardKernel();
RegisterServices();
}
private static void RegisterServices()
{
_kernel.Load(new UtilAndServiceModule());
}
}
public class TestManager
{
internal static IDapperHelper _iDapperHelper = NInjectBase.Kernel.Get();
public void Test()
{
_iDapperHelper.Execute(sqlCommand:"SP_GET_DOCUMENTS", commandType:CommandType.StoredProcedure);
}
}
3和4做的事跟以下代码做的是一样的。
--Microsoft.Extensions.DependencyInjection提供了三种生命周期:
builder.Services.AddScoped
(); builder.Services.AddSingleton (); builder.Services.AddTransient ();
using DependencyInjection.Example;
using Microsoft.Extensions.DependencyInjection;
HostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton();
using IHost host = builder.Build();
host.Run();
5做的事同以下代码是一样的
using Microsoft.Extensions.DependencyInjection;
public class TestManager
{
private readonly IDapperHelper _iDapperHelper;
public TestManager (IDapperHelper helper)
{
_iDapperHelper = helper
}
public void Test()
{
_iDapperHelper.Execute(sqlCommand:"SP_GET_DOCUMENTS", commandType:CommandType.StoredProcedure);
}
}
Transient lifetime services are created each time they're requested from the service container. To register a service as transient, call AddTransient.
In apps that process requests, transient services are disposed at the end of the request. This lifetime incurs per/request allocations, as services are resolved and constructed every time. For more information, see Dependency Injection Guidelines: IDisposable guidance for transient and shared instances.
For web applications, a scoped lifetime indicates that services are created once per client request (connection). Register scoped services with AddScoped.
In apps that process requests, scoped services are disposed at the end of the request.
When using Entity Framework Core, the AddDbContext extension method registers DbContext
types with a scoped lifetime by default.
Singleton lifetime services are created either:
Every subsequent request of the service implementation from the dependency injection container uses the same instance. If the app requires singleton behavior, allow the service container to manage the service's lifetime. Don't implement the singleton design pattern and provide code to dispose of the singleton. Services should never be disposed by code that resolved the service from the container. If a type or factory is registered as a singleton, the container disposes the singleton automatically.
Register singleton services with AddSingleton. Singleton services must be thread safe and are often used in stateless services.
In apps that process requests, singleton services are disposed when the ServiceProvider is disposed on application shutdown. Because memory is not released until the app is shut down, consider memory use with a singleton service.