jjzjj

c# - Autofac - 自动注册错误 : No constructors can be found with 'Public binding flags'

coder 2024-05-20 原文

这是我的 Global.asax.cs

public void RegisterContainersUsingAutofac()
    {
        //http://elegantcode.com/2009/01/07/ioc-libraries-compared/
        //http://www.codeproject.com/Articles/25380/Dependency-Injection-with-Autofac
        //https://code.google.com/p/autofac/
        //http://api.autofac.org/
        var builder = new ContainerBuilder();
        builder.RegisterModelBinders(Assembly.GetExecutingAssembly());
        builder.RegisterModelBinderProvider();
        //builder.RegisterType<AuthenticationService>().As<IAuthenticationService>();
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        //builder.RegisterAssemblyTypes(typeof(SecurityService).Assembly).
        //      Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerHttpRequest();
        builder.RegisterType(typeof(UnitOfWork)).As(typeof(IUnitOfWork)).InstancePerLifetimeScope()
            .OnRelease(x =>{((IUnitOfWork)x).Commit();});

        builder.RegisterAssemblyTypes(typeof(UserRepository).Assembly).Where(t => t.Name.EndsWith("Repository")).AsImplementedInterfaces();
        builder.RegisterAssemblyTypes(typeof(SecurityService).Assembly).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();

        IContainer container = builder.Build();
        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    }

我遇到了以下错误: 找不到带有“公共(public)绑定(bind)标志”的“AppBase.Service.UserService”类型的构造函数。

我注册了已实现的存储库和服务接口(interface),但哪里出错了?它在以下中断。

这是我的用户服务

 public interface IUserService
{
    int Login(string userNameOrEmail, string password, out int errorcode, out int timeout);
    bool Register(string userName, string password, string email, string country, string language, out int errorCode);

    bool Register(User user, out int errorCode);
    bool ResetPassword(string username, string email, string oldPassword, string newPassword, out int errorCode);

    void DeleteUser(string userName);
}
public class UserService : IUserService
{
      private readonly IUserRepository userRepository;
     private UserService(IUserRepository _userRepository)
    {
        userRepository = _userRepository;

    }
    //other methods ...

}

这是我的错误:

 [DependencyResolutionException: No constructors on type 'AppBase.Service.UserService' can be found with 'Public binding flags'.]
 Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +261
 Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +91
 Autofac.Core.Resolving.InstanceLookup.Execute() +135
 Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +434
 Autofac.Core.Resolving.InstanceLookup.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +61
 Autofac.Core.Activators.Reflection.<>c__DisplayClass2.<CanSupplyValue>b__0() +68
 Autofac.Core.Activators.Reflection.ConstructorParameterBinding.Instantiate() +201
             Autofac.Core.Activators.Reflection.ReflectionActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) +499
 Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) +91
 Autofac.Core.Resolving.InstanceLookup.Execute() +135
 Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) +434
 Autofac.Core.Resolving.ResolveOperation.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +52
 Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) +115
 Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) +300
 Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) +103
 Autofac.ResolutionExtensions.ResolveOptionalService(IComponentContext context, Service service, IEnumerable`1 parameters) +218
 Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType, IEnumerable`1 parameters) +64
 Autofac.ResolutionExtensions.ResolveOptional(IComponentContext context, Type serviceType) +43
 Autofac.Integration.Mvc.AutofacDependencyResolver.GetService(Type serviceType) +49
 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +51

 [InvalidOperationException: An error occurred when trying to create a controller of type 'AppBase.Web.Controllers.AccountController'. Make sure that the controller has a parameterless public constructor.]
 System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
 System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
 System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
 System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
 System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
 System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
 System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
 System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
  System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8968180
 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

最佳答案

我不确定为什么 UserService 有一个私有(private)构造函数。是否有一个原因?

通过定义构造函数,不再生成默认构造函数public UserService()

Autofac 只会注入(inject)公共(public)构造函数,而您现在没有这些构造函数。如果您将其更改为公开,它应该会起作用。

关于c# - Autofac - 自动注册错误 : No constructors can be found with 'Public binding flags' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10972932/

有关c# - Autofac - 自动注册错误 : No constructors can be found with 'Public binding flags'的更多相关文章

  1. ruby-on-rails - 使用 Ruby on Rails 进行自动化测试 - 最佳实践 - 2

    很好奇,就使用ruby​​onrails自动化单元测试而言,你们正在做什么?您是否创建了一个脚本来在cron中运行rake作业并将结果邮寄给您?git中的预提交Hook?只是手动调用?我完全理解测试,但想知道在错误发生之前捕获错误的最佳实践是什么。让我们理所当然地认为测试本身是完美无缺的,并且可以正常工作。下一步是什么以确保他们在正确的时间将可能有害的结果传达给您? 最佳答案 不确定您到底想听什么,但是有几个级别的自动代码库控制:在处理某项功能时,您可以使用类似autotest的内容获得关于哪些有效,哪些无效的即时反馈。要确保您的提

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  5. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  6. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  7. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  8. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  9. ruby-on-rails - 新 Rails 项目 : 'bundle install' can't install rails in gemfile - 2

    我已经像这样安装了一个新的Rails项目:$railsnewsite它执行并到达:bundleinstall但是当它似乎尝试安装依赖项时我得到了这个错误Gem::Ext::BuildError:ERROR:Failedtobuildgemnativeextension./System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/rubyextconf.rbcheckingforlibkern/OSAtomic.h...yescreatingMakefilemake"DESTDIR="cleanmake"DESTDIR="

  10. ruby-on-rails - rspec should have_select ('cars' , :options => ['volvo' , 'saab' ] 不工作 - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion在首页我有:汽车:VolvoSaabMercedesAudistatic_pages_spec.rb中的测试代码:it"shouldhavetherightselect"dovisithome_pathit{shouldhave_select('cars',:options=>['volvo','saab','mercedes','audi'])}end响应是rspec./spec/request

随机推荐