我正在尝试使用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的构造函数。感谢。
答案 0 :(得分:2)
添加专用绑定应该可以解决问题:
kernel.Bind<ITestAlert>()
.ToConstant(new TestAlert{FullName = Dummy"}).WhenInjectedInto<ValuesController>();