我是 Ninject 的新手。它在调用常规依赖类时效果很好。
但是,我无法在自定义反射中调用依赖项。
我也尝试过构造函数注入。它抛出异常 -No parameterless constructor defined for this object.
我怎样才能实现它?如果有更好的技术,我愿意改变我的设计。
谢谢!
这里是入口点
请注意以下代码仅用于演示 -
var squareCalculation = Activator.CreateInstance(
Type.GetType("SquareCalculation")) as ICalculation;
int square = squareCalculation.Calculate(1);
var multiplyByTwoCalculation = Activator.CreateInstance(
Type.GetType("MultiplyByTwoCalculation")) as ICalculation;
int multiply = multiplyByTwoCalculation.Calculate(2);
计算
public interface ICalculation
{
int Calculate(int number);
}
public class SquareCalculation : ICalculation
{
// SquareService is not injecting.
[Inject]
public ISquareService SquareService { get; set; }
public int Calculate(int number)
{
// *** This is the method I would like to call. It is unique. ****
SquareService.Monday(1);
return number * number;
}
}
public class MultiplyByTwoCalculation : ICalculation
{
// MultiplyByTwoService is not injecting.
[Inject]
public IMultiplyByTwoService MultiplyByTwoService { get; set; }
public int Calculate(int number)
{
// *** This is the method I would like to call. It is unique. ****
MultiplyByTwoService.Tuesday(1, 2, "a");
return number * 2;
}
}
Ninject App_Start
这只是我通过 NuGet 下载的默认设置。
[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(MyApp.App_Start.NinjectWebCommon), "Stop")]
namespace MyApp.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
.....
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ISquareService>().To<SquareService>().InSingletonScope();
kernel.Bind<IMultiplyByTwoService>().To<MultiplyByTwoService>().InSingletonScope();
}
}
}