无参数的公共构造函数

时间:2014-12-04 16:35:07

标签: c# asp.net-mvc asp.net-mvc-5 unity-container

首次使用MS Unity。我有一个带有以下构造函数的控制器:

 protected IAdministrationService AdministrationService { get; set; }

 public GenerateCacheController(IAdministrationService administrationService)
 {
    AdministrationService = administrationService;
 }

尝试运行项目时出现以下错误:

确保控制器具有无参数的公共构造函数。

在我的Bootstrpper.cs文件中,我在RegisterTypes方法中有以下内容:

container.RegisterType<GenerateCacheController>();

我仍然得到错误。我错过了什么吗?我使用的是ASP.NET MVC 5和Unity 3。

这是我的Boostrapper.cs文件:

 public static class Bootstrapper
{
    public static IUnityContainer Initialise()
    {
        var container = BuildUnityContainer();
        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
        return container;
    }

    private static IUnityContainer BuildUnityContainer()
    {
        var container = new UnityContainer();
        RegisterTypes(container);
        return container;
    }

    public static void RegisterTypes(IUnityContainer container)
    {
        container.RegisterInstance(container);
        var im = new InjectionMember[0];
        container.RegisterType<IAdministrationService, AdministrationService>("AdministrationService", im);
        container.RegisterType<ILookupMapper, LookupMapper>("LookupMapper", im);
        container.RegisterType<IEmailService, EmailService>("EmailService", im);

        container.RegisterType<GenerateCacheController>();

        var provider = new UnityServiceLocator(container);
        ServiceLocator.SetLocatorProvider(() => provider);
    }
}

AdministrationService类的缩写版本:

 public class AdministrationService : IAdministrationService
{
    protected ILookupMapper LookupMapper { get; set; }
    protected IEmailService EmailService { get; set; }

    public AdministrationService(ILookupMapper lookupMapper, IEmailService emailService)
    {
        LookupMapper = lookupMapper;
        EmailService = emailService;
    }
}

1 个答案:

答案 0 :(得分:0)

发现了这个问题。

我评论了这一行:

 var im = new InjectionMember[0];
 container.RegisterType<IAdministrationService, AdministrationService>("AdministrationService", im);

并补充说:

container.RegisterType<IAdministrationService, AdministrationService>();

这很有效,因为之前的开发人员正在做这样的事情:

private IUnityContainer Container { get; set; }

public AdministrationService()
{
    Container = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IUnityContainer>();
}

而不是

protected ILookupMapper LookupMapper { get; set; }
protected IEmailService EmailService { get; set; }

public AdministrationService(ILookupMapper lookupMapper, IEmailService emailService)
{
    LookupMapper = lookupMapper;
    EmailService = emailService;
}

我必须回到他们不破坏现有代码的方式。我有一天会去重构。