带构造函数的自定义成员资格提供程

时间:2014-09-15 06:59:28

标签: c# asp.net-mvc-4 structuremap

我在我的MVC项目中添加了一个自定义成员资格提供程序:

<membership defaultProvider="CodeFirstMembershipProvider">
  <providers>
    <add name="CodeFirstMembershipProvider" type="CodeFirstMembershipProvider" />
  </providers>
</membership>

我还使用DI,IoC(使用结构图)从我的数据库中获取数据,所以我需要在我的自定义成员资格类中使用这样的构造函数:

public class CodeFirstMembershipProvider : MembershipProvider
{
    private readonly IUnitOfWork _uow;
    private readonly IAccount _acc;

    public CodeFirstMembershipProvider(IUnitOfWork uow, IAccount acc)
    {
        _uow = uow;
        _acc = acc;
    }

但问题是,当我运行我的项目并尝试使用CodeFirstMembershipProvider类的任何方法时,我收到此错误: No parameterless constructor defined for this object

我该如何解决这个问题?

编辑1:
我改变了这样的构造函数:

public CodeFirstMembershipProvider()
{
    _uow = ServiceLocator.Current.GetInstance<IUnitOfWork>();
    _acc = ServiceLocator.Current.GetInstance<IAccount>();
}

但我仍然收到此错误:Exception has been thrown by the target of an invocation

编辑2: 我的IoC课程:

public static class IoC
{
    public static IContainer Initialize()
    {
        ObjectFactory.Initialize(x =>
        {
            x.Scan(scan =>
            {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
            });
            x.For<IUnitOfWork>().HttpContextScoped().Use<DbContext>();
            x.For<IAccount>().Use<AccountService>();
        });
        return ObjectFactory.Container;
    }
}

1 个答案:

答案 0 :(得分:1)

好的,我最终使用了ObjectFactory.GetInstance并继续前进。我不知道这种方式是最佳做法还是后来遇到问题,但这就是我的构造函数现在的样子:

    using StructureMap;
    private readonly IUnitOfWork _uow;
    private readonly IAccount _acc;

    public CodeFirstMembershipProvider()
    {
        _uow = ObjectFactory.GetInstance<IUnitOfWork>();
        _acc = ObjectFactory.GetInstance<IAccount>();
    }