【发布时间】:2017-08-23 15:47:06
【问题描述】:
这是我解决依赖关系的类
namespace TestProj
{
public static class Bootstrapper
{
public static void Run()
{
SetAutofacWebAPI();
}
private static void SetAutofacWebAPI()
{
var builder = new ContainerBuilder();
builder.RegisterType<UserService>().As<IUserService>().InstancePerRequest();
builder.RegisterType<Encryption>().As<IEncryption>().InstancePerRequest();
DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
}
}
}
在 Global.asax 中,我有这个:Bootstrapper.Run();
这是我的 UserService 类:
public class UserService : IUserService
{
private readonly IEncryption _Encryption;
public UserService(Encryption Encryption)
{
_Encryption = Encryption;
}
//Rest of the service here
}
Encryption 类是类似的。
控制器就在这里:
public class UserController : Controller
{
private readonly IUserService _UserService;
public AccountController(UserService UserService)
{
_UserService = UserService;
}
public JsonResult GetLoginLogs(int Id)
{
var Logs = _UserService.GetLoginLogById(Id);
return Json(Logs, JsonRequestBehavior.AllowGet);
}
//The rest of the controller
}
这是版本信息:
Autofac : 3.5.2
MVC : 4.0.40804.0
DOTNET : 4
然后,当尝试localhost:5000/Account/GetLoginLogs/1 时出现此异常:
没有为此对象定义无参数构造函数。
请有人帮忙。我遇到了严重的麻烦!
【问题讨论】:
-
我认为您对如何显式注入类感到困惑。注入依赖类时使用接口而不是具体类
-
您将
UserService注册为IUserService。您也未能注册您的 MVC 控制器。 -
检查link,与上面的艾米在同一行
-
感谢@Amy 你的评论很有帮助!
标签: c# .net asp.net-mvc-4 dependency-injection autofac