简体   繁体   English

依赖注入:没有为此定义无参数构造函数 object

[英]Dependency Injection: No parameterless constructor defined for this object

I am attempting to use dependency injection (.NET Framework 4.6, ASP.NET MVC), but I am getting the error: No parameterless constructor defined for this object. If I also provide a parameterless constructor for HomeController then _token is null.我正在尝试使用依赖项注入(.NET Framework 4.6、ASP.NET MVC),但出现错误: No parameterless constructor defined for this object.如果我还为HomeController提供无参数构造函数,则_token为 null。

How I properly provide this object via dependency injection?我如何通过依赖注入正确提供这个 object?

Owin Startup.cs:欧文 Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<IGenerateToken, GenerateTokenService>();
}

Controller: Controller:

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);
    }
}

GenerateTokenService:生成令牌服务:

public ueSecurityToken GenerateToken(string key, string pin)
{
    var token = new ueSecurityToken
    {
        SourceKey = key,
        ClientIP = new WebClient().DownloadString("http://bot.whatismyipaddress.com/")
    };

    var hash = new ueHash
    {
        Type = "md5",
        Seed = Guid.NewGuid().ToString()
    };
    var input = string.Concat(token.SourceKey, hash.Seed, pin); // combine data into single string
    // Create a new instance of the MD5CryptoServiceProvider object.
    var md5Hasher = MD5.Create();
    // Convert the input string to a byte array and compute the hash.
    var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
    // Create a new Stringbuilder to collect the bytes
    // and create a string.
    var sBuilder = new StringBuilder();
    // Loop through each byte of the hashed data 
    // and format each one as a hexadecimal string.
    foreach (var t in data)
    {
        sBuilder.Append(t.ToString("x2"));
    }
    hash.HashValue = sBuilder.ToString();
    token.PinHash = hash;
    return token;
}

public interface IGenerateToken
{
    ueSecurityToken GenerateToken(string key, string pin);
}

Sure you can use DI.当然你可以使用DI。 I prefer Simple Injector because it is simple and most cases it covers all the scenarios.我更喜欢 Simple Injector,因为它很简单,而且大多数情况下它涵盖了所有场景。 For more and advancing you can use Autofac or Ninject.如需更多和进步,您可以使用 Autofac 或 Ninject。

But your method in controller it not hit by the DI.但是你在控制器中的方法没有被 DI 击中。 They set the constructors for the classes.他们为类设置构造函数。 So your DI has no use in this case.所以你的 DI 在这种情况下没有用。

Instead of a comment... the DI can't resolve this, and thus you get an error :) What does GenerateToken do?而不是评论... DI 无法解决这个问题,因此您会收到一个错误:) GenerateToken 做什么? Is this a static function/class?这是一个静态函数/类吗? You might want to create an interface:您可能想要创建一个接口:

public interface IGenerateToken
{ 
    string GenerateToken();
}

and a class:和一个班级:

public class GenerateTokenService : IGenerateToken
{
  //your logic
}

then in your DI you can add a singleton for creating a token:然后在您的 DI 中,您可以添加一个单例来创建令牌:

services.AddSingleton<IGenerateToken, GenerateTokenService >();

And in your constructur:在你的构造中:

private readonly IGenerateToken _token;

public HomeController(IGenerateToken token)
{
    _token = token;
}

This makes testing also better :)这使得测试也更好:)

Try it!试试看!

With ASP.NET 6 you might also get this error with a Blazor/Razor component.ASP.NET 6中,Blazor/Razor 组件也可能出现此错误。 The component needs the empty constructor.该组件需要空的构造函数。

To solve this, you can use a property and mark it with Inject like this:为了解决这个问题,您可以使用一个属性并用Inject标记它,如下所示:

[Inject]
protected IDataAccess DataRepository { get; set; }

More info: Microsoft Docs更多信息: 微软文档

Ran into a similar problem, after digging out found the article above.遇到了类似的问题,挖掘后找到了上面的文章。 I had to modify the method BuildUnityContainer to register my service.我必须修改 BuildUnityContainer 方法来注册我的服务。

See: https://learn.microsoft.com/en-us/as.net/mvc/overview/older-versions/hands-on-labs/as.net-mvc-4-dependency-injection请参阅: https://learn.microsoft.com/en-us/as.net/mvc/overview/older-versions/hands-on-labs/as.net-mvc-4-dependency-injection

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 添加Owin后,依赖注入中断,没有为此对象定义的无参数构造函数 - Dependency Injection broken after adding Owin, no parameterless constructor defined for this object WCF:没有为此对象依赖注入Simple Injector定义的无参数构造函数 - WCF: no parameterless constructor defined for this object dependency injection Simple Injector 没有为此对象定义无参数构造函数 - No parameterless constructor defined for this object 没有为此对象定义无参数构造函数。 当我尝试使用 Unity 依赖时 - No parameterless constructor defined for this object. while i try for Unity Dependency automapper 中没有为此 object 定义无参数构造函数 - No parameterless constructor defined for this object in automapper 错误:未为此对象定义无参数构造函数 - Error: No parameterless constructor defined for this object 在mvc中没有为此对象定义无参数构造函数 - No parameterless constructor defined for this object in mvc MissingMethodException:没有为此对象定义无参数构造函数 - MissingMethodException: no parameterless constructor defined for this object 奇怪的错误:没有为此对象定义无参数构造函数 - Strange error: No parameterless constructor defined for this object 温莎城堡-没有为此对象定义无参数的构造函数 - castle windsor - No parameterless constructor defined for this object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM