如何使用Ninject将Initialized Instance传递给Web API Controller的构造函数

时间:2017-11-08 02:42:48

标签: asp.net-web-api dependency-injection ninject self-hosting

我正在尝试使用Ninject将依赖注入自主Web API控制器。我成功地将依赖注入如下:

    public static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();

        try
        {
            kernel.Bind<ITestAlert>().To<TestAlert>();
            return kernel;
        }
        catch (Exception)
        {
            throw;
        }
    }

    var server = WebApp.Start(baseAddress, (appBuilder) =>
    {
        // Configure Web API for self-host.
        var config = new HttpConfiguration();

        config.DependencyResolver = new NinjectResolver(NinjectConfig.CreateKernel());

        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
        );
        appBuilder.UseWebApi(config);
    });

但是,我想要做的是将一个初始化的实例从外部传递给Controller的构造函数。例如,我初始化了一个实例

public interface ITestAlert
{
    string Fullname { get; set; }
}

public class TestAlert : ITestAlert
{
    private string _fullname;

    public string Fullname
    {
        get
        {
            return _fullname;
        }
        set
        {
            _fullname = value;
        }
    }
}

实例初始化为

public ITestAlert _testAlert;

_testAlert = new TestAlert
{
    FullName = "Dummy"
};

我期望从Controller的Get action方法获取“Dummy”输出字符串,

 private ITestAlert _testAlert = null;

 public ValuesController(ITestAlert testAlert)
 {
     _testAlert = testAlert;
 }

 public string Get()
 {
     return _testAlert.Fullname;
 }

但是,我只能获得“空”回报!您能否告诉我如何将初始化的实例传递给Controller的构造函数。感谢。

1 个答案:

答案 0 :(得分:2)

添加专用绑定应该可以解决问题:

kernel.Bind<ITestAlert>() .ToConstant(new TestAlert{FullName = Dummy"}).WhenInjectedInto<ValuesController>();