DDD: injecting IPrincipal into service and repository layers - domain-driven-design

I am currently working on a DDD-based application using Unity IOC container and need a way to pass my custom Principal object to the repository and service layers that would allow for unit testing. How should this be done? My current thoughts are to create a property on the service and repository classes of type IPrincipal. Then use Unity on Application_Start to set and pass in the Principal.
For one, am I on the right track in my thinking?
Two, if not at application_start, which seems like that is not the right place since I need a person to login first before the injections occur, where should this occur?
Three, for Unity, what should the container.RegisterType look like for getting the Principal from Thread.CurrentPrincipal or HttpContext.Current.User?

You can have a PrincipalDto class that will contain the relevant IPrincipal properties you need to use in your Service layer and map the values from the IPrincipal to the PrincipalDto. This way you do not need to include the reference assembly of IPrincipal to the other layers.
Below is an example that uses auto mapping.
public class PrincipalDto
{
public UserId { get; set; }
public Username { get; set; }
public RoleId { get; set; }
}
public class SomeService
{
public void SomeServiceMethod(PrincipalDto principal)
{
// do work here
}
}
public class SomeConsumer()
{
public void SomeConsumerMethod()
{
// where User is the IPrincipal object instance
var principal = Mapper.Map<PrincipalDto>(User);
var service = new Service();
service.SomeServiceMethod(principal);
}
}

Related

How to initialize sub-collections along with aggregate root in abp.io

What I want to achieve is to figure out where to initialize my sub-collections with aggregate root itself and validate business rules in a best practice way.
Here is my AppService:
public async Task<ReservationDto> CreateReservationAsync(CreateReservationInputDto input)
{
var reservation = await _reservationSystemManager.CreateAsync(
input.ReserverNotes
);
//should i send them directly to manager's createasync method but RequestedItems are dto objects.
//should i iterate through RequestedItems here and send them to manager one by one.
// where to throw business exception if RequestedItems count is 0.
}
Here is my inputdto:
public class CreateReservationInputDto
{
public string ReserverNotes { get; set; }
public Enum.Status Status { get; set; }
public List<CreateReservationItemInputDto> RequestedItems { get; set; }
}
Here is my aggregate root:
public class Reservation : FullAuditedAggregateRoot<Guid>
{
public Enum.Status Status { get; private set; }
public string ReserverNote { get; private set; }
public ICollection<ReservationItem> ReservationItems { get; set; }
public ICollection<OverduePayment> OverduePayments { get; set; }
private Reservation() { }
internal Reservation(
Guid id,
Enum.Status status,
[NotNull] string reserverNote,
) : base(id)
{
ReserverNote = reserverNote;
Status = status;
ReservationItems = new Collection<ReservationItem>();
OverduePayments = new Collection<OverduePayment>();
}
//I could not decide where and how to call this function from Domain Service.
internal void AddReservationItem(ReservationItem reservationItem)
{
if (ReservationItems.Any(r => r.Id == reservationItem.Id))
{
return;
}
ReservationItems.Add(reservationItem);
}
}
Well, depends on your business rules and your use cases. For example, if a reservation must have some reservation items, then I would create it in reservation constructor. Otherwise, if after creating reservation I can add new reservation items then I would be another use case and then AddReservationItem has sense for me.
Generally, if you need to inject more than one service (E.g. IUserRepository and IReservationItemsRepository) for validating your collection or any other property, you can create a domain service and implement your business logic and validate your collection with your needs.
If you don't need to inject any service to implement your business rules you can do it directly in your application service methods. In such cases, you can use data annotations for validating your properties in DTO classes as stated in here.
//should i send them directly to manager's createasync method but RequestedItems are dto objects.
//should i iterate through RequestedItems here and send them to manager one by one.
//where to throw business exception if RequestedItems count is 0.
In these three questions you've asked, should take it separately.
For instance, If you create a domain service class, it could be better to throw an exception if the RequestedItems count is 0 in that class' method. (And you can call, your AddReservationItem method from the domain service's method in that case.)
You can also check the best-practices documents of ABP.

Unity Container resolve a Dictionary of objects with same Interface

I got the following block
container.RegisterType<IService, ServiceA>("a");
container.RegisterType<IService, ServiceB>("b");
I want to have a Dictionary of type Dictionary<string,IService>.
I will receive service name by parameter in an API rest and my idea is based on that parameter get the implementation I need from the Dictionary.
I can't figure out how to inject the Dictionary (with the resolved classes inside) into my business class.
I want to do something like this.
private readonly IDictionary<string,IService> serviceDictionary;
public ClassConstructor (IDictionary<string,IService> dictionary)
{
this.serviceDictionary = dictionary;
}
You should not inject IDictionary<string,IService> into your component, but instead an application-tailored abstraction:
public interface IServiceProvider
{
IService GetService(string key);
}
This way you can create an implementation for Unity as follows:
public class UnityServiceProvider : IServiceProvider
{
public IUnityContainer Container { get; set; }
public IService GetService(string key) => Container.Resolve<IService>(key);
}
Now you can complete your registration as follows:
container.RegisterType<IService, ServiceA>("a");
container.RegisterType<IService, ServiceB>("b");
container.RegisterInstance<IService>(new UnityServiceProvider { Container = container });
container.RegisterType<ClassConstructor>();

(ServiceStack) Location of business logic in a message based architecture

What is the best practice for placing business logic in message based design?
Im using servicestack for building my api.
The wiki shows the example of placing the RequiredRole Attribute on the message instead of the service handling it.
In a sense this [RequiredRole]/[Authenticate] is business logic/security attached to the message.
Concrete example
Say for example i would add DeleteAddress message:
public class DeleteAddress : IReturn<bool>
{
public int AddressId { get; set; }
}
But for this to be properly secure i want to check either Admin Role, permission to ManageAllAddresses or that the AddressId is linked to this user (maybe in session, maybe through a db call).
How would i best go about this?
Proposition
Is the following code the good practice and if so how would i implement it?
[RequiredRole("Admin")]
[RequiredPermission("ManageAllAddresses ")]
[RequiredAddressLinkedToAccount]
public class DeleteAddress : IReturn<bool>
{
public int AddressId { get; set; }
}
ServiceStack's recommendation is to keep your ServiceModel free of dependencies so we'd recommend to annotate your Service implementation classes instead which you can annotate either on the Service class to apply to all Operations or on the individual methods to apply just to that operation, e.g:
[RequiredRole("Admin")]
public class AddressServices : Service
{
[RequiredPermission("ManageAllAddresses ")]
[RequiredAddressLinkedToAccount]
public object Any(DeleteAddress request)
{
}
}
Please note ServiceStack requires your Services to return reference types, which is typically a Response DTO but can also be a string, e.g:
public class DeleteAddress : IReturn<string>
{
public int AddressId { get; set; }
}
To finish of this question. I could make a request filter and add it on the service.
Either inherit from AuthenticateAttribute or Directly from RequestFilterAttribute.
public class RequiredAddressLinkedToAccount : AuthenticateAttribute
{
public RequiredRoleAttribute(ApplyTo applyTo)
{
this.ApplyTo = applyTo;
this.Priority = (int)RequestFilterPriority.RequiredRole;
}
public override void Execute(IRequest req, IResponse res, object requestDto)
{
var dto = requestDto as ILinkedToAccount;
var session = req.GetSession();
if(dto.AccountId == session.Id)
return; //we dont want anything to be blocked if the account Id is there.
//Implement like RequireRoleAttribute
if (DoHtmlRedirectIfConfigured(req, res))
return;
res.StatusCode = (int)HttpStatusCode.Forbidden;
res.StatusDescription = "Address does not belong to you";
res.EndRequest();
}
}

CRUD and Query with ServiceStack - Need to get rid of some confusion

I am a bit confused with ServiceStack 'old' and 'new' API and need some clarification and best practices, especially with Request / Response DTO's and routing. I watched some courses on Pluralsight and have the first three books listet on servicestack.net in my electronic bookshelf.
I like to 'restify' an existing application which is built using DDD patterns which means I have a high level of abstraction. The client is WPF and follows the MVVM pattern. I have 'client side service', 'server side service' and repository classes (and some aggregates too). I use NHibernate 4 (with fluent API and a code-first approach) as ORM. Only my repository classes know about the ORM. I have DTO's for all my Entity objects and in my WPF client I only work with those DTOs in the ViewModel classes. I heavily use AutoMapper to 'transfer' Entity objects to my DTO's and vice versa.
My confusion starts exactly with these DTO's and the Request / Response DTOs used in ServiceStack. Here is a very much simplified example of an Address Entity which illustrates the problem:
All my Entity Objects derive from EntityBase which contains basic properties used in all Entities:
public abstract class EntityBase : IEntity
{
public virtual Guid Id { get; protected set; }
public virtual DateTime CDate { get; set; } //creation date
public virtual string CUser { get; set; } //creation user
public virtual DateTime MDate { get; set; } //last modification date
public virtual string MUser { get; set; } //last modification user
//
// some operators and helper methods irrelevant for the question
// ....
}
public class Address : EntityBase
{
public string Street { get; private set; }
public string AdrInfo1 { get; private set; }
public string AdrInfo2 { get; private set; }
public string ZipCode { get; private set; }
public string City { get; private set; }
public string Country { get; private set; }
}
Of course there are collections and references to related objects which are ignored here as well as database mappers, naming conventions etc. The DTO I have looks like this:
public class AddressDto
{
public Guid Id { get; set; } // NHibernate GUID.comb, NO autoincrement ints!!
public DateTime CDate { get; set; }
public string CUser { get; set; }
public DateTime MDate { get; set; }
public string MUser { get; set; }
public string Street { get; private set; }
public string AdrInfo1 { get; private set; }
public string AdrInfo2 { get; private set; }
public string ZipCode { get; private set; }
public string City { get; private set; }
public string Country { get; private set; }
}
To use this with ServiceStack I need to support the following:
CRUD functionality
Filter / search functionality
So my 'Address service' should have the following methods:
GetAddresses (ALL, ById, ByZip, ByCountry, ByCity)
AddAddress (Complete AddressDTO without Id. CDate, CUser are filled automatically without user input)
UpdateAddress (Complete AddressDTO without CUser and CDate, MDate and MUser filled automatically without user input)
DeleteAddress (Just the Id)
For me it is pretty clear, that all Requests return either a single AddressDto or a List<AddressDto> as ResponseDTO except for the delete which should just return a status object.
But how to define all those RequestDTO's? Do I really have to define one DTO for EACH scenario?? In the books I only saw samples like:
[Route("/addresses", "GET")]
public class GetAddresses : IReturn<AddressesResponse> { }
[Route("/addresses/{Id}", "GET")]
public class GetAddressById : IReturn<AddressResponse>
{
public Guid Id { get; set; }
}
[Route("/addresses/{City}", "GET")]
public class GetAddressByCity : IReturn<AddressResponse>
{
public string City { get; set; }
}
// .... etc.
This is a lot of boilerplate code and remembers me a lot of old IDL compilers I used in C++ and CORBA.....
Especially for Create and Update I should be able to 'share' one DTO or even better reuse my existing DTO... For delete there is probably not much choice....
And then the filters. I have other DTOs with a lot more properties. A function approach like used in WCF, RPC etc is hell to code...
In my repositories I pass an entire DTO and use a predicate builder class which composes the LINQ where clause depending on the properties filled. This looks something like this:
List<AddressDto> addresses;
Expression<Func<Address, bool>> filter = PredicateBuilder.True<Address>();
if (!string.IsNullOrEmpty(address.Zip))
filter = filter.And(s => s.Zip == address.Zip);
// .... etc check all properties and dynamically build the filter
addresses = NhSession.Query<Address>()
.Where(filter)
.Select(a => new AddressDto
{
Id = a.Id,
CDate = a.CDate,
//.... etc
}).ToList();
Is there anything similar I could do with my RequestDTO and how should the routing be defined?
A lot of questions raised here have been covered in existing linked answers below. The Request / Response DTOs are what you use to define your Service Contract, i.e. instead of using RPC method signatures, you define your contract with messages that your Service accepts (Request DTO) and returns (Response DTO). This previous example also walks through guidelines on designing HTTP APIs with ServicesStack.
Use of well-defined DTOs have a very important role in Services:
You want to ensure all types your Services return are in DTOs since this, along with the base url of where your Services are hosted is all that's required for your Service Consumers to know in order to consume your Services. Which they can use with any of the .NET Service Clients to get an end-to-end Typed API without code-gen, tooling or any other artificial machinery.
DTOs are what defines your Services contract, keeping them isolated from any Server implementation is how your Service is able to encapsulate its capabilities (which can be of unbounded complexity) and make them available behind a remote facade. It separates what your Service provides from the complexity in how it realizes it. It defines the API for your Service and tells Service Consumers the minimum info they need to know to discover what functionality your Services provide and how to consume them (maintaining a similar role to Header files in C/C++ source code). Well-defined Service contracts decoupled from implementation, enforces interoperability ensuring that your Services don't mandate specific client implementations, ensuring they can be consumed by any HTTP Client on any platform. DTOs also define the shape and structure of your Services wire-format, ensuring they can be cleanly deserialized into native data structures, eliminating the effort in manually parsing Service Responses.
Auto Queryable Services
If you're doing a lot of data driven Services I recommend taking a look at AutoQuery which lets you define fully queryable Services without an implementation using just your Services Request DTO definition.

Understanding Asp.Net Identity key points

I am an Asp.net developer but very much new to the Asp.net Identity framework. I have been studying the sample application and followed some tutorials too on Identity but still I am not able to grasp the concept completely. I have very firm grip over Asp.net membership but Identity seems nothing like membership. I will explain what I have done so far.
I am creating a simple application in which I am following code first approach. I have created entity model for User which inherits from IdentityUser and has some extra fields. Below is entity model for User.
public class User : IdentityUser
{
public int? CompanyID { get; set; }
public bool? CanWork { get; set; }
public bool? CanSearch { get; set; }
public Company Company { get; set; }
}
Now in the examples people use the name ApplicationUser but for my own purpose I have used name User. Also there is a method in User or ApplicationUser model which is,
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
{
CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
I am unable to understand the purpose of this method. Also from an example I have used the following model for Role,
public class Role : IdentityRole
{
public Role()
{
}
public Role(string roleName, string description)
: base(roleName)
{
this.Description = description;
}
public string Description { get; set; }
}
I understand that an extra field is added but I am unable to understand the purpose of overloaded constructor.
The above mentioned confusions are secondary. My primary confusion is that I am familiar that when I create entity models I use DbSet and DbContext and when I call any entity framework method to access the database, the database is created/drop created whichever scheme I am following.
In Identity which method is responsible for creating the Identity tables in the database? I have a IdentityConfig file in which I declare ApplicationUserManager and ApplicationSignInManager. I have also a Startup file. Previously I had only one Startup file in the App_Start folder and when I run the application and tried to accessed any Identity methods it gave me error and was not creating database. I then made the class as partial and created another partial class with same name at the root and then the exception was gone and tables were created. So Startup class is responsible for creating Identity tables? There are extra columns created automatically in the AspNetUsers like PhoneNumber, PhoneNumberConfirmed, TwoFactorEnabled. I don't need these extra columns. Can I remove these? Can I change the names of the Identity tables that are created?
I know these are very basic questions and not one question at all but if I was unable to find some basic tutorial or example for beginners then it would be very beneficial. What I have found are describing those things which I don't need or making me confuse. I want to understand and have control how Identity should work in my application but till now it seems to me that neither I am grasping it completely and nor being able to make is adjustable to my needs. Its like tutorials and example are teaching me how to make sentences but I am unable to understand the alphabets. :(
First of all you have to define the model - as you're doing - implementing the right interfaces.
Let's say you want to create a user for your application:
public class MyUser : IdentityUser<string, MyUserLogin, MyUserRole, MyUserClaim>
{
public string CompanyName { get; set; }
}
As you can see I've implemented the IdentityUser interface (namespace Microsoft.AspNet.Identity.EntityFramework).
I've specified what type of identifier I want to use for my primary key (string) and included my custom objects to manges login, roles and claims.
Now we can defined the role object:
public class MyRole : IdentityRole<string, MyUserRole>
{
}
Again there's a type and the class I've defined for the management of users belonging to to a role.
public class MyUserRole : IdentityUserRole<string>
{
}
MyUserLogin is going to implement IdentityUserLogin<string>.
MyUserClaim is going to implement IdentityUserClaim<string>.
As you can see each interface need a type for the primary key.
The second step is to create the user store:
public class MyUserStore: UserStore<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
public MyUserStore(MyContext context)
: base(context)
{
}
}
Again we have defined what user, role, login etc etc we want to use.
We need UserStore cause our UserManager is going to need one.
If you're planning to manage roles and associate roles with each user you have to create your RoleStore definition.
public class MyRoleStore : RoleStore<MyRole, string, MyUserRole>
{
public DaufRoleStore(ApplicationDatabaseContext context) : base(context)
{
}
}
Now you can create your UserManager. The UserManager is the real responsible of saving changes to the UserStore.
public class ApplicationUserManager : UserManager<MyUser, string>
{
public ApplicationUserManager(IUserStore<MyUser, string> store)
: base(store)
{
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new MyUserStore(context.Get<MyContext>()));
manager.UserValidator = new UserValidator<MyUser, string>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
manager.PasswordValidator = new PasswordValidator()
{
RequiredLength = 5,
RequireNonLetterOrDigit = false, // true
// RequireDigit = true,
RequireLowercase = false,
RequireUppercase = false,
};
return (manager);
}
}
This class has a static method which will create a new UserManager for you.
Interesting to note that you can include some validation rules you might need to validate password etc etc.
Last thing is to create or database context.
public class MyContext : IdentityDbContext<MyUser, MyRole, string, MyUserLogin, MyUserRole, MyUserClaim>
{
public MyContext(): base("<your connection string here>")
{
}
public static MyContext Create()
{
return new MyContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<MyUser>()
.ToTable("Users");
modelBuilder.Entity<MyRole>()
.ToTable("Roles");
modelBuilder.Entity<MyUserRole>()
.ToTable("UserRoles");
modelBuilder.Entity<MyUserClaim>()
.ToTable("UserClaims");
modelBuilder.Entity<MyUserLogin>()
.ToTable("UserLogins");
}
}
As you can see I've used the model builder to change the names all the tables.
You can define keys or fields type or tables relations here.
This is the place where you're going to attach your custom classes you want to manage in your context:
public DbSet<MyCustomer> Customers{ get; set; }
Again MyContext has a Create method which returns a new context:
public static MyContext Create()
{
return new MyContext();
}
Now you should have a startup class where you're going to bootstrap your stuff:
[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]
namespace ASPNETIdentity2
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.CreatePerOwinContext(MyContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
}
}
}
Here you're going to create your database context and your user manager you can use in your application.
Notice the first line:
[assembly: OwinStartup(typeof(ASPNETIdentity2.Startup))]
This is needed cause you're telling your environment that is the startup class which needs to be called at ... startup.
Now in your controllers you can simply refer to your UserManager doing something like this:
HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
How can you create your tables?
In Visual Studio go to TOOLS -> NuGet Packager Manager -> Package Manager Console.
In the window there's a combobox "Default Project". Choose your ASP.NET MVC project.
Run this command:
Enable-Migrations
It will create a file Configuration.cs in a new folder called Migrations.
If you want to create your database you need to open that file and change the AutomaticMigrationsEnabled to true:
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
Again, from Package Manager Console, you can run:
Update-Database
and all your tables will appear in your database. Don't forget your connection string.
You can download this github project to see how everything works.
You can check these two answers with some other info.
The first of the two has got some links to a blog where you can learn all these things.
NOTE:
You have to do all this if you want to customized every single bit of your environment.

Resources