Essentially, I want to be able to determine the namespace of the caller class inside my service. The service instantiation happens with the default ASP.NET Core DI. A further obstacle may arise because I want to determine the caller inside the constructor of the base class and not directly in the instantiated service.
I suspect I know the answer to my question, but if It can happen, it wouldn't be the crazier thing I've seen.
Edit
Sample code
// First caller
namespace Example.Assembly.One
{
public class CallerOne
{
consctructor(Service service)
void WhichCallerAmI() { return this.service.ReturnCaller() }
...
}
}
// Second caller
namespace Example.Assembly.Two
{
public class CallerTwo
{
consctructor(Service service)
void WhichCallerAmI() { return this.service.ReturnCaller() }
...
}
}
// Service
namespace Example.Service
{
public class Service : BaseService
{
consctructor() : base()
public void ReturnCaller()
{
if (this.namespace == "Example.Assembly.One")
{
return "First caller";
}
return "Second caller";
}
}
}
// Base service
namespace Example.Service
{
public class BaseService
{
consctructor(Service service)
{
// Determine namespace of caller here
this.namespace = <insert-answer-here>
}
}
}
// demo
// These callers can be controllers or other services
var firstCaller = new CallerOne()
var secondCaller = new CallerTwo();
// firstResult now contains "First Caller"
var firstResult = firstCaller.WhichCallerAmI();
// secondResult now contains "Second Caller";
var secondResult = secondCaller.WhichCallerAmI();
XY problem
The Callers from the example represent data services in separete micro-service web projects, each using separate database. The problem I am trying to work around is to reuse the same service code for one entity, duplicated in all or some of the separate databases. My idea is to inject the relevant DbContext
based on the namespace of the caller class, since we follow strict naming conventions either way.