MVC存储库,Unity,身份错误

时间:2016-12-11 05:06:03

标签: asp.net-mvc-5 unity-container dapper asp.net-identity-2

我正在使用MVC 5,Identity 2.x,Unity和Dapper开始一个新项目。我正在使用Identity的标准EF功能,但使用Dapper进行其余的数据库访问。我正在为所有(非身份)数据库调用使用存储库模式。

我是Unity和Dapper的新手,但每当我拨打电话时,请保持“ 对象引用未设置为对象的实例。 ”错误从下面的帐户控制器行中的数据库接口:

var result = _companyaccountrepository.AddToCompanyUsers(model);

有谁可以指出我做错了什么?提前谢谢。

帐户控制器

private ICompanyAccountRepository _companyaccountrepository { get; set; }

public ICompanyAccountRepository companyaccountrepository
{
    get { return _companyaccountrepository ?? (_companyaccountrepository = new CompanyAccountRepository());  }
}

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}


private ApplicationSignInManager _signInManager;

public ApplicationSignInManager SignInManager
{
    get
    {
        return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
    }
    private set { _signInManager = value; }
}

public AccountController()
{

}

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ICompanyAccountRepository companyaccountrepository)
{
    UserManager = userManager;
    SignInManager = signInManager;
    _companyaccountrepository = companyaccountrepository;
}

...

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SignUp(RegisterUserAndCompanyViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };

        user.FirstName = model.FirstName;
        user.LastName = model.LastName;

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {

            await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

            var result = _companyaccountrepository.AddToCompanyUsers(model);   //*** THIS IS WHERE THE PROBLEM OCCURS ****

            return RedirectToAction("Confirmation");

        }
        AddErrors(result);
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

接口/ Dapper SQL(虚拟代码使其变得简单)

public interface ICompanyAccountRepository
{
    CompanyUser AddToCompanyUsers(RegisterUserAndCompanyViewModel user);

}


public class CompanyAccountRepository : ICompanyAccountRepository
{
    private string dbconn = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public bool AddToCompanyUsers(RegisterUserAndCompanyViewModel user);
    {
        using (SqlConnection cn = new SqlConnection(dbconn))
        {
            cn.Open();
            cn.Insert(new CompanyUser() { CompanyId = user.companyid, UserId = user.id });
            cn.Close();

        }

        return true;

    }

}

Unity.Config

public static void RegisterTypes(IUnityContainer container)
{
    // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
    // container.LoadConfiguration();

    // TODO: Register your types here

    //12-1-16 Need this for Identity
    container.RegisterType<ApplicationDbContext>();
    container.RegisterType<ApplicationSignInManager>();
    container.RegisterType<ApplicationUserManager>();
    container.RegisterType<EmailService>();

    container.RegisterType<IAuthenticationManager>(
        new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
        new InjectionConstructor(typeof(ApplicationDbContext)));


    container.RegisterType<AccountController>(
        new InjectionConstructor(typeof(ApplicationUserManager), typeof(ApplicationSignInManager), typeof(ICompanyAccountRepository)));

    container.RegisterType<AccountController>(
            new InjectionConstructor());


    //Identity / Unity stuff below to fix No IUserToken Issue  - http://stackoverflow.com/questions/24731426/register-iauthenticationmanager-with-unity
    //container.RegisterType<DbContext, ApplicationDbContext>(
    //    new HierarchicalLifetimeManager());
    container.RegisterType<UserManager<ApplicationUser>>(
        new HierarchicalLifetimeManager());
    container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
        new HierarchicalLifetimeManager());

        container.RegisterType<ICompanyAccountRepository, CompanyAccountRepository>();

}

再次感谢您的任何建议。

注意:如果我在AddToCompanyUsers调用之前添加实例化存储库(如下所示),它可以正常工作。但是,这打破了Unity / IOC

_companyaccountrepository= new CompanyAccountRepository();
var result = _companyaccountrepository.AddToCompanyUsers(model);

1 个答案:

答案 0 :(得分:0)

你可以这样试试:

(这应该可以解决您的存储库错误。至于您的userManager和signInManager,我相信您也可以改进它们的配置方式,但是这需要查看您的startup.auth和您的ApplicationDbContext以及所有身份配置)

帐户控制器

private readonly ICompanyAccountRepository _companyaccountrepository;// { get; set; } -- remove the getter and setter here



//remove this

// public ICompanyAccountRepository companyaccountrepository
// {
//     get { return _companyaccountrepository ?? (_companyaccountrepository = new CompanyAccountRepository());  }
// }

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}


private ApplicationSignInManager _signInManager;

public ApplicationSignInManager SignInManager
{
    get
    {
        return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
    }
    private set { _signInManager = value; }
}

//I think you can remove the parameterless constructor as well
//public AccountController()
//{
//
//}

public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager, ICompanyAccountRepository companyaccountrepository)
{
    UserManager = userManager;
    SignInManager = signInManager;
    _companyaccountrepository = companyaccountrepository;
}

...

修改

将构造函数更改为:

public AccountController(ICompanyAccountRepository companyaccountrepository)
{
    _companyaccountrepository = companyaccountrepository;
}