我有一個由DAL,BLL和API層組成的應用程序,以及使用統一注入的Iam。在業務層,我有一個名爲AuthRepository的類,它從IAuthRepository繼承,下面是這個類的一部分。在三層應用程序中使用Unity
類AuthRepository在BLL:
public class AuthRepository : IAuthRepository, IDisposable
{
private UserAuthContext _authContext;
private UserManager<UserInfo> _userManager;
// Issue 1: this constructor should be delete and use injection instead
// to solve the problem in class SimpleAuthorizationServerProvider
public AuthRepository()
{
_authContext = new UserAuthContext();
_userManager = new UserManager<UserInfo>(new UserStore<UserInfo>(_authContext));
}
public AuthRepository(UserAuthContext authContext)
{
_authContext = authContext;
//this._authContext = new UserAuthContext();
_userManager = new UserManager<UserInfo>(new UserStore<UserInfo>(_authContext)); // TODO: implement usermanager with Unity
}
public async Task<IdentityResult> RegisterUser(UserEntity createUserModel)
{
UserInfo user = new UserInfo
{
FirstName = createUserModel.FirstName,
LastName = createUserModel.LastName,
UserName = createUserModel.UserName,
Email = createUserModel.Email
};
var result = await _userManager.CreateAsync(user, createUserModel.Password);
return result;
}
在API層I具有另一個類被稱爲SimpleAuthorizationServerProvider,類照顧由Owin以下提供的熊的令牌類
類SimpleAuthorizationServerProvider在API層中:
public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
// Resource owner password credentials does not provide a client ID.
if (context.ClientId == null)
{
context.Validated();
}
return Task.FromResult<object>(null);
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
using (AuthRepository _repo = new AuthRepository())
{
IdentityUser user = await _repo.FindUser(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
}
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
identity.AddClaim(new Claim("sub", context.UserName));
identity.AddClaim(new Claim("role", "user"));
context.Validated(identity);
}
}
問題是AuthRepository中的第一個構造函數應該是remov編輯使應用程序耦合。如果我刪除此構造方法,所以我需要在此聲明
使用發送從方法GrantResourceOwnerCredentials的SimpleAuthorizationServerProvider類類型UserAuthContext的參數(AuthRepository _repo =新AuthRepository())
和這就是我不想做的,API層應該與BLL進行通信而不是DAL。
任何想法如何解決這個問題?
這就是其實我試圖這樣做,但是當我在啓動類註冊SimpleAuthorizationServerProvider,我也會面臨同樣的問題,即構造函數中SimpleAuthorizationServerProvider需要IAuthRepository類型的參數。你是否認爲帶有propreties而不是構造函數的DI可以解決這個問題? –
你應該使用'RegisterType()'註冊'IAuthRepository'的具體類,如下所示:'yourContainer.RegisterType ();' –
venerik
我做了bro,我已經完成了這一步。我的問題是,我必須在GrantResourceOwnerCredentials方法的SimpleAuthorizationServerProvider類中發送UserAuthContext類型的參數 –