Problem: My application is built upon clean architecture. I want to create a new instance of a class in my lower layer, but the class itself resides in an upper layer. The upper layer can depend on lower layer, but the lower layer can not depend on a upper one.
Why: That's because, AuthorizationService
requires new instance of requirement. These requirements sit in API layer (upper). And my resource based authorization happens in services that are situated in Application layer (lower).
My solution: I created factory pattern.
EDIT: I changed name of factory to be generic.
EDIT2: I changed factory pattern to simple factory.
THIS IS SITUATED IN SERVICE / APPLICATION LAYER
var testFactory = _requirementFactory.Create("MemberOwnerOnlyRequirement");
var testListReq = new List<IAuthorizationRequirement>(){testFactory}; // Testing
var authorization = await _authorizationService.AuthorizeAsync(_currentUserService.MemberIdentity, member, //Testing
testListReq);
THESE INTERFACES ARE IN INTERFACES / APPLICATION LAYER
public interface IRequirementFactory
{
IAuthorizationRequirement Create(string requirementType);
}
THESE CONCRETE CLASSES ARE IN AUTHORIZATION / API LAYER
public class RequirementFactory : IRequirementFactory
{
public IAuthorizationRequirement Create(string requirementType)
{
switch (requirementType)
{
case "MemberOwnerOnlyRequirement":
return new MemberOwnerOnlyRequirement();
default:
return null;
}
}
}
public class MemberOwnerOnlyRequirement : IAuthorizationRequirement
{
}
I'm a beginner and I pursue clean code & best practices. My friend, who's a mid-level asp.net developer suggested bending the rule & create same class in Application layer, thus violating DRY.
Could you please suggest other approach / review mine?