Autofac Multi-tenant IoC Container in an ASP.NET Web API Application - asp.net

Autofac 3.0 will have a MultitenantIntegration support and its preview release is out now. To try it out, I created an ASP.NET Web API application with the following configuration:
public class Global : System.Web.HttpApplication {
protected void Application_Start(object sender, EventArgs e) {
var config = GlobalConfiguration.Configuration;
config.Routes.MapHttpRoute("Default", "api/{controller}");
RegisterDependencies(config);
}
public void RegisterDependencies(HttpConfiguration config) {
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// creates a logger instance per tenant
builder.RegisterType<LoggerService>().As<ILoggerService>().InstancePerTenant();
var mtc = new MultitenantContainer(
new RequestParameterTenantIdentificationStrategy("tenant"),
builder.Build());
config.DependencyResolver = new AutofacWebApiDependencyResolver(mtc);
}
}
It gets the job done and creates a LoggerService instance as ILoggerService per tenant. I have two problems at this stage which I wasn't able to solve:
I used out of the box provided RequestParameterTenantIdentificationStrategy here as the TenantIdentificationStrategy just for this demo application. I am able to create my custom TenantIdentificationStrategy by implementing ITenantIdentificationStrategy interface. However, TryIdentifyTenant method of the ITenantIdentificationStrategy makes you rely on a static instance such as HttpContext.Current which is something that I don't want in an ASP.NET Web API environment as I want my API to be hosting agnostic (I know that I can delegate this work to the hosting layer but I would rather not to). Is there another way to achieve this in a way that I won't rely on a static instance?
I also have a chance to register tenant specific instance as below:
mtc.ConfigureTenant("tenant1", cb => cb.RegisterType<Foo>()
.As<IFoo>().InstancePerApiRequest());
However, one of my situations requires me to pass the tenant name through the constructor parameter and I would love to have something like below:
mtc.ConfigureTenant((cb, tenantName) => cb.RegisterType<Foo>()
.As<IFoo>()
.WithParameter("tenantName", tenantName)
.InstancePerApiRequest());
Currently there is no such an API. Is there another way to achieve this or this kind of requirement doesn't make any sense?

Multitenant support has been available for a long time, it's just that 3.0 is the first time we've had a NuGet package for it. :)
The RequestParameterTenantIdentificationStrategy is, as documented, just a very simple example showing one possible (and not recommended) way to identify tenant. You will have to choose for yourself how to identify your tenant based on the operating context. It could be from a web.config value, an environment variable, or some other thing in the current environment. If you don't want to use HttpContext.Current, don't. It's up to you to pick where you get that info from.
(A note on the RPTIStrategy - the part that isn't recommended is using a querystring or request parameter as the tenant ID mechanism. I use HttpContext in my production apps and it works fine. There's only so much you can abstract out before you have to actually touch the bare metal.)
There is no way out of the box to provide the lambda registration syntax you're asking for, primarily because tenant is not passed through the resolution process. The resolution process is:
Identify the tenant with the strategy.
Find the tenant's configured lifetime scope.
Use standard Autofac Resolve style syntax.
It's intentionally simple and analogous to the existing operations. At the time of resolve, the sub-lifetime-scope belonging to the tenant is tagged with the tenant ID but the resolution operation doesn't know about the tenant ID... so the lambda wouldn't work (and probably won't anytime soon because it'd change the fundamental internals of the way Autofac works if it did).
To accomplish what you're looking for, you can use a combination of the InstancePerTenant extension when registering...
var builder = new ContainerBuilder();
builder.RegisterType<Foo>().As<IFoo>().InstancePerTenant();
...and registering the ITenantIdentificationStrategy as a dependency in your container.
builder.Register(myIdStrategy).As<ITenantIdentificationStrategy>();
Then make your class take an ITenantIdentificationStrategy rather than the tenant ID directly. Use the strategy to get the tenant ID instead.
If you REALLY want to get fancy, you could register a keyed lambda that resolves the ID strategy, then gets the tenant ID. Then you could add a parameter registration to the object like you did but using a keyed service. (I'm going to go by memory now, so you'll have to double-check my syntax here, but it'll be something like this...)
builder.Register(c =>
{ var s = c.Resolve<ITenantIdentificationStrategy>();
object id;
s.TryIdentifyTenant(out id);
return id;
}).Keyed<object>("tenantId");
builder.RegisterType<Foo>()
.As<IFoo>()
.WithParameter(
(pi, c) => pi.Name == "tenantId",
(pi, c) => c.ResolveKeyed<object>("tenantId"))
.InstancePerApiRequest();
Again, you'll want to double-check me on that, but I'm pretty sure that (or a minor variation) should work to get you what you want.

Related

How to configure multiple UserManager with different DbContext

I'm struggling with Net Core Identity, more specifically the UserManager API. I have two databases with the same logic structure, one of them is for testing and homologation purposes. I looked around for a good while and managed to somehow make the segregated access work under the same application, creating a "homologation ambient". Since I still have to perform user and role-related management, authentication, and other tasks, it is in my interest to keep the same functions of the default UserManager, but looking at a different database. And now I'm stuck with this: the GeneratePasswordResetTokenAsync() method from UserManager fails, depending on how I set the StartUp.cs:
StartUp.cs
services.Configure<IdentityOptions>(opt =>
{
opt.User.RequireUniqueEmail = true;
opt.Password.RequiredLength = 8;
opt.Lockout.AllowedForNewUsers = false;
opt.SignIn.RequireConfirmedAccount = true;
opt.SignIn.RequireConfirmedEmail = true;
opt.Tokens.PasswordResetTokenProvider = "passwordReset";
opt.Tokens.EmailConfirmationTokenProvider = "emailConfirmation";
});
services.AddIdentity<User, IdentityRole>()
.AddEntityFrameworkStores<DNDriveContext>()
.AddTokenProvider<TwoFactorTokenProvider<User>>("passwordReset")
.AddTokenProvider<EmailConfirmationTokenProvider<User>>("emailConfirmation");
services.AddIdentityCore<UserHom>()
.AddRoles<IdentityRole>()
.AddClaimsPrincipalFactory<UserClaimsPrincipalFactory<UserHom, IdentityRole>>()
.AddEntityFrameworkStores<DNDriveHomContext>()
.AddTokenProvider<TwoFactorTokenProvider<UserHom>>("passwordReset")
.AddTokenProvider<EmailConfirmationTokenProvider<UserHom>>("emailConfirmation");
Through my research on the topic, I came across the AddIdentityCore<TUser>() method above, and it works fine in creating a second UserManager<TUser> that I can access in the controller via DI. The roles work fine too, and I can perform token validations segregated from the "production" environment, but the moment I try to call GeneratePasswordResetTokenAsync(), I get the following error:
No IUserTwoFactorTokenProvider named 'passwordReset' is
registered.
I tried passing the IdentityOptions to each Identity individually instead of calling services.Configure<IdentityOptions>, but it didn't make a difference. I assume this is an issue of assignment since only one of the UserManagers works at a time. With the above configuration, UserManager<UserHom> will successfully generate the reset password token, but the main UserManager<User> will throw the above-mentioned error. Commenting the two AddTokenProvider<> at the end of AddIdentityCore<UserHom> fixes the main UserManager, but now the homologation one fails.
I'm aware of the possibility of making a custom UserManager, but as I said in the beginning, I would like to keep all the default functions of UserManager, and I have no idea of how to start implementing one of my own. What exactly is the explanation for what is happening and how do I fix this?

Getting IMetadataDetailsProviders to Run More than Once in ASP.NET Core

This is a tricky question which will require some deep knowledge of the ASP.NET Core framework. I'll first explain what is happening in our application in the MVC 3 implementation.
There was a complex requirement which needed to be solved involving the ModelMetaData for our ViewModels on a particular view. This is a highly configurable application. So, for one "Journal Type", a property may be mandatory, whereas for another, the exact same property may be non-mandatory. Moreover, it may be a radio-button for one "Journal Type" and a select list for another. As there was a huge number of combinations, mixing and matching for all these configuration options, it was not practical to create a separate ViewModel type for each and every possible permutation. So, there was one ViewModel type and the ModelMetaData was set on the properties of that type dynamically.
This was done by creating a custom ModelMetadataProvider (by inheriting DataAnnotationsModelMetadataProvider).
Smash-cut to now, where we are upgrading the application and writing the server stuff in ASP.NET Core. I have identified that implementing IDisplayMetadataProvider is the equivalent way of modifying Model Metadata in ASP.NET Core.
The problem is, the framework has caching built into it and any class which implements IDisplayMetadataProvider only runs once. I discovered this while debugging the ASP.NET Core framework and this comment confirms my finding. Our requirement will no longer be met with such caching, as the first time the ViewModel type is accessed, the MetadataDetailsProvider will run and the result will be cached. But, as mentioned above, owing to the highly dynamic configuration, I need it to run prior to every ModelBinding. Otherwise, we will not be able to take advantage of ModelState. The first time that endpoint is hit, the meta-data is set in stone for all future requests.
And we kinda need to leverage that recursive process of going through all the properties using reflection to set the meta-data, as we don't want to have to do that ourselves (a massive endeavour beyond my pay-scale).
So, if anyone thinks there's something in the new Core framework which I have missed, by all means let me know. Even if it is as simple as removing that caching feature of ModelBinders and IDisplayMetadataProviders (that is what I'll be looking into over the next couple of days by going through the ASP.NET source).
Model Metadata is cached due to performance considerations. Class DefaultModelMetadataProvider, which is default implementation of IModelMetadataProvider interface, is responsible for this caching. If your application logic requires that metadata is rebuilt on every request, you should substitute this implementation with your own.
You will make your life easier if you inherit your implementation from DefaultModelMetadataProvider and override bare minimum for achieving your goal. Seems like GetMetadataForType(Type modelType) should be enough:
public class CustomModelMetadataProvider : DefaultModelMetadataProvider
{
public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider)
: base(detailsProvider)
{
}
public CustomModelMetadataProvider(ICompositeMetadataDetailsProvider detailsProvider, IOptions<MvcOptions> optionsAccessor)
: base(detailsProvider, optionsAccessor)
{
}
public override ModelMetadata GetMetadataForType(Type modelType)
{
// Optimization for intensively used System.Object
if (modelType == typeof(object))
{
return base.GetMetadataForType(modelType);
}
var identity = ModelMetadataIdentity.ForType(modelType);
DefaultMetadataDetails details = CreateTypeDetails(identity);
// This part contains the same logic as DefaultModelMetadata.DisplayMetadata property
// See https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Metadata/DefaultModelMetadata.cs
var context = new DisplayMetadataProviderContext(identity, details.ModelAttributes);
// Here your implementation of IDisplayMetadataProvider will be called
DetailsProvider.CreateDisplayMetadata(context);
details.DisplayMetadata = context.DisplayMetadata;
return CreateModelMetadata(details);
}
}
To replace DefaultModelMetadataProvider with your CustomModelMetadataProvider add following in ConfigureServices():
services.AddSingleton<IModelMetadataProvider, CustomModelMetadataProvider>();

ASP.Net MVC 6: Recursive Dependency Injection

Still exploring the new ASP.NET MVC5, now with build in DI!
No Problem so far, I can just inject my Handlers (I don't like the Term Service, since this defines to me a Platform-Neutral Interface):
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
services.AddMvc();
}
Works fine, also the strongly typed Configuration-Object "AppSettings" works perfectly fine.
Also the Injection in the Controllers works as well.
But now my collaps: I seperated my DataAccess from the Handlers, and obviously I'd like to inject them as well:
public class UserEndPointConfigurationHandler
{
private readonly DataAccess.UserEndPointAccess _access;
public UserEndPointConfigurationHandler(DataAccess.UserEndPointAccess access)
{
_access = access;
}
But bam, UserEndPointAccess can't be resolved. So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that. For this case, sure I should Interface and register them, but what does that mean for internal helper classes I also inject?
According to the Docs: http://docs.asp.net/en/latest/fundamentals/dependency-injection.html#recommendations and also the examples I found, all people in the world only seem to communicate between Controllers and some Repositories. No Business-Layer and no Classes on different Abstraction-Levels in Assemblies.
Is the Microsoft DI approach something totally differnt than the good ol' Unity one, where I can really decouple as fine granular as I'd like to?
Thanks in advance.
Matthias
Edit #Nightowl: I add my answer here, since it's a bit longer.
First of all, Unity does automatically create Instances, if I request a conecrete Type. This allows me to inject Types I register and Types, like Helper classes etc. I don't need to. This combination allows me to use DI everywhere.
Also in your Example I'd need to know the DataAcces in the WebGui, which is quite thight coupled. Well, I know there are solutions for this via Reflection, but I hoped Microsoft did something in this Topic, but probably that'd mean to big of a change.
Also allows Unity to store Instances or Instructions how to create them, another huge feature, which is missing at the moment.
Probably I'm just to spoiled, what refined DI-Libraries do, probably they also do to much, but at the moment the Microsoft-Implementation is just a huge downgrade according to my Information.
MVC Core follows the the composition root pattern, which is where object graphs are created based off of a set of instructions to instantiate them. I think you are misinterpreting what the IServiceCollection is for. It does not store instances, it stores instructions on how to create instances. The instances aren't actually created until a constructor somewhere in the object graph requests one as a constructor parameter.
So, in short the reason why your service (which you call UserEndPointAccess) is not being instantiated when you request it is because you have not configured the IServiceCollection with instructions on how to create it.
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddApplicationInsightsTelemetry(Configuration);
services.Configure<Model.Meta.AppSettings>(Configuration.GetSection("AppSettings"));
services.AddSingleton(typeof(Logic.UserEndPointConfigurationHandler));
services.AddSingleton(typeof(Logic.NetworkHandler));
// Need a way to instantiate UserEndPointAccess via DI.
services.AddSingleton(typeof(DataAccess.UserEndPointAccess));
services.AddMvc();
}
So it seems like even I directly request to DI an Class with a Parameterless-Constructor, I need to register that.
If you are doing DI correctly, each service class will only have a single constructor. If you have more than one it is known as the bastard injection anti-pattern, which essentially means you are tightly coupling your class definition to other classes by adding references to them as foreign defaults.
And yes, you need to register every type you require (that is not part of MVC's default registration). It is like that in Unity as well.

Configure Autofac Container for background thread

I have an asp.net MVC site which has many components registered using an InstancePerHttpRequest scope, however I also have a "background task" which will run every few hours which will not have an httpcontext.
I would like to get an instance of my IRepository which has been registered like this
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerHttpRequest();
How do I do this from a non http context using Autofac? I think the IRepository should use the InstancePerLifetimeScope
There are several ways of how you can do that:
The best one in my opinion. You can register the repository as InstancePerLifetimeScope as you said. It works with HttpRequests and LifetimeScopes equally well.
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Your registration for HttpRequest may differ from registration for LifetimeScope, then you can have two separate registrations:
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.WithParameter(...)
.InstancePerHttpRequest(); // will be resolved per HttpRequest
builder.RegisterGeneric(typeof(EfRepository<>)).As(typeof(IRepository<>))
.InstancePerLifetimeScope(); // will be resolved per LifetimeScope
You can explicitly create "HttpRequest" scope using its tag. Exposed through MatchingScopeLifetimeTags.RequestLifetimeScopeTag property in new versions.
using (var httpRequestScope = container.BeginLifetimeScope("httpRequest")) // or "AutofacWebRequest" for MVC4/5 integrations
{
var repository = httpRequestScope.Resolve<IRepository<Entity>>();
}

Handling security and be decoupled

I am trying to design an application in 3 layers :
1) Data access layer
2) business layer
3) UI
I try to keep classes decoupled so on the business layer I have created interfaces for the Data access classes like this :
public interface ICountryRepository:IRepository
{
Country GetCountry(int ID);
int CreateCountry(Country obj);
Boolean UpdateCountry(Country obj);
Boolean DeleteCountry(Country obj);
...
...
}
and i pass the interface as param to the service constructor :
public CountryService(ICountryRepository repository,ILanguageRepository lang_repository)
{
....
}
But on the CountryService for example I need to load the current user and his permissions so I can check if the operation can be applied :
public Country GetCountry(int ID)
{
if securityService.UserHasPermission(currentUser, GetPermission("CanGetCountry"))
{
return repository.GetCountry(ID);
}
else
{
Throw(New SecurityException("No permissions for that operation ...."))
}
}
That means I have to instantiate the SecurityDataAccess object and pass it to the constructor of the SecurityService on my business layer assembly which I try to avoid for keeping objects decoupled. Right now I even don't have a reference to any DataAccess assembly on my business assembly.
I am thinking of using an IoC container here. Using external configuration I could get the right class/assembly from a config file. But I am not sure that is the right solution because it is said that IoC containers should be used in one place to keep things simple and it should be the top level assembly (the UI assembly) most of the time.
Anybody has a suggestion for solving this problem ?
Why not add the security service into the constructor of the Country service? That way the IOC Container could resolve the dependency and inject the security if it is needed. That mean the IOC Container would take care of constructing your CountryService object. And you would use the container to get all Services.
Another option could be to "normalize" your repository a bit...
Trim it down to it only has 4-5 basic functions that are identical for all repositories, then use generics to make them all look alike, so no
UpdateCountry(...)
but
Update(T object)
Something like this:
http://codebetter.com/blogs/gregyoung/archive/2009/01/16/ddd-the-generic-repository.aspx
Then you can use a Chain of reponsibilty pattern to place your security code before the DB Code ( http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern )
So you could have a SecurityChecker that validates access, throws an exception if invalid, or passes down the request in the next link in the chain (You can also add a logging dynamically that way, or timing or whatever)
Do you need to implement security in the Data Access layer? If you move your security service to the business layer as Heiko suggests. In other words, perform security in the business layer and you avoid the IoC issue altogether.
This may be off-beam, apologies if it is, I'm a lurking Java EE programmer. It seems to me that authorisation is of methods is better addressed in the infrastructure, declaratively.
This article appears to suggest that .Net, like Java EE offers a facility to control access declaratively. Does this approach work for you?

Resources