我正在尝试使用依赖注入(.NET Framework 4.6,ASP.NET MVC),但我收到错误:No parameterless constructor defined for this object.
如果我还为HomeController
提供了无参数构造函数,那么{{ 1}}为空。
Owin Startup.cs:
_token
控制器:
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IGenerateToken, GenerateTokenService>();
}
GenerateTokenService:
public class HomeController : Controller
{
private readonly ueSecurityToken _token;
public HomeController(ueSecurityToken token)
{
_token = token;
}
public async Task<ActionResult> RunCreditCard()
{
var client = new UsaEPayClient();
var request = new TransactionRequestObject
{
CreditCardData = new CreditCardData()
{
CardNumber = "4000100011112224",
CardExpiration = "0919",
CardCode = "123"
}
};
var response = await client.runSaleAsync(_token, request);
return View(response);
}
}
答案 0 :(得分:1)
当然可以使用DI。我更喜欢Simple Injector,因为它很简单,大多数情况下它涵盖了所有场景。如需更多信息并推进,可以使用Autofac或Ninject。
但你在控制器中的方法没有被DI击中。他们为类设置构造函数。所以你的DI在这种情况下没有用。
答案 1 :(得分:0)
而不是评论...... DI无法解决此问题,因此您收到错误:) GenerateToken做什么?这是一个静态函数/类吗?您可能想要创建一个界面:
curl -v http://localhost:3000/currentVideo
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /currentVideo HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json; charset=utf-8
< Content-Length: 58
< ETag: W/"3a-FMsS5hMXa1tcIFnGeYHinQ"
< Date: Sun, 18 Sep 2016 20:34:04 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
{"youtubeSrc":"https://www.youtube.com/embed/9Q-ovNuireY"}
和一个班级:
public interface IGenerateToken
{
string GenerateToken();
}
然后在你的DI中你可以添加一个单例来创建一个令牌:
public class GenerateTokenService : IGenerateToken
{
//your logic
}
在你的构造中:
services.AddSingleton<IGenerateToken, GenerateTokenService >();
这使测试更好:)
试试吧!