ASP.NET Web Api使用Ninject实现依赖注入


二、使用步骤

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值