Ninject在Asp.net Web API 2中的依赖注入
二、使用步骤
1.引入库
Ninject
Ninject.Web.Common
Ninject.Web.WebApi
Ninject.Web.Common.WebHost
安装完Ninject.Web.Common.WebHost包后,会在App_Start文件夹中自动生成Ninject.Web.Common.cs 文件,该文件实现Ninject初始化相关的内容
2.编辑Ninject.Web.Common.cs 文件
代码如下(示例):
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
//配置IOC解析器
GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
添加上述代码后,在项目的Controller的构造函数中使用依赖注入,才会生效。否则失败
3. 注册相关服务
定义接口IExcelUtilityRepository.cs
public interface IExcelUtilityRepository
{
DataTable ExcelToDataTable(string filename);
}
实现接口
ExcelUtilityRepository.cs
public class ExcelUtilityRepository: IExcelUtilityRepository
{
public DataTable ExcelToDataTable(string filename)
{
var filePath = System.Web.Hosting.HostingEnvironment.MapPath($@"/RelationConfigs/{filename}");
FileStream fs = null;
IWorkbook workbook = null;
DataTable dataTable = null;
try
{
if (filePath == null)
{
LogManager.GetCurrentClassLogger().Info($"filepath is null");
return null;
}
if (!File.Exists(filePath))
{
LogManager.GetCurrentClassLogger().Info($"{filePath} not exists");
return null;
}
using (fs = File.OpenRead(filePath))
{
if (filename != null && filename.IndexOf(".xlsx", StringComparison.Ordinal) > 0)
{
workbook = new XSSFWorkbook(fs);
}
else if (filename != null && filename.IndexOf(".xls", StringComparison.Ordinal) > 0)
{
workbook = new HSSFWorkbook(fs);
}
var sheet = workbook?.GetSheetAt(0); //獲取一個工作頁
if (sheet != null)
{
dataTable = new DataTable();
var rowCount = sheet.LastRowNum; //獲取行數
if (rowCount <= 1) return null;//空白sheet或者只含有column行
var firstRow = sheet.GetRow(0); //獲取列名稱
var cellCount = firstRow.LastCellNum; //獲取列數
//創建列
ICell cell;
var startRow = 1;
for (int i = firstRow.FirstCellNum; i < cellCount; i++)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
var column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
//內容填充
for (int i = startRow; i <= rowCount; i++)
{
var row = sheet.GetRow(i);
if (row == null)
{
continue;
}
var dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
return dataTable;
}
catch (Exception e)
{
fs?.Close();
return null;
}
}
}
在NinjectWebCommon.cs中的 RegisterServices(…)方法中注册对应的服务
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IProductRepository>().To<ProductRepository>().InTransientScope();
kernel.Bind<ISapHelper>().To<SapHelper>().InTransientScope();
kernel.Bind<IDbConnection>().To<OracleConnection>();
kernel.Bind<IExcelUtilityRepository>().To<ExcelUtilityRepository>();
kernel.Bind<IOracleConnectionFactory>().To<OracelConnectionFactory>();
kernel.Bind<IEnergyRepository>().To<EnergyRepository>();
kernel.Bind<IMapper>().ToMethod(context =>
{
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile<MappingProfile>();
cfg.ConstructServicesUsing(t => kernel.Get(t));
});
return config.CreateMapper();
}).InTransientScope();
//kernel.Bind<ILog>().To<Log>().WithConstructorArgument("currentClassName",
// x => x.Request.ParentContext.Request.Service.FullName);
}
## 4.控制器使用
public class UserController : ApiController
{
private IExcelUtilityRepository _excelService;
public UserController(IExcelUtilityRepository excel)
{
_excelService= excel;
}
public DataTable Get()
{
return _userService.ExcelToDataTable(filepath);
}
}
参考文献
[https://coderminer.com/blog/post/39cb1036c2680e68090852f818e50e45]