1

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?

user1790300
  • 2,143
  • 10
  • 54
  • 123
  • What is a principal in your business? Looks like you are polluting your domain model with technical terms or you are missing a bounded context. – plalx Nov 17 '14 at 13:56
  • The principal refers to the User credentials of the currently logged in user. – user1790300 Nov 18 '14 at 17:57
  • It was more of a rhetorical question to make you realize that a Principal is probably not a business term. That concept should be translated to one that makes sense for your domain. What kind of operation will you perform with the Principal? – plalx Nov 18 '14 at 19:06

1 Answers1

0

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);
    }
}
Ronald
  • 1,532
  • 4
  • 18
  • 34
  • The only thing about this is that I am trying to seamlessly make the service layer and repository layer aware of the user without passing parameters. – user1790300 Nov 07 '14 at 15:40