I want to know who does call/create constructor of PageModel-derived class (in my case IndexModel).
Seems to me that by each request to a razor page, the class which is provided to the RazorPage via #model is instantiated, also wanna know who supplies the constructor parameter context, which is the EF Context:
public IndexModel(RazorPagesMovie.Models.RazorPagesMovieContext context)
{
_context = context;
}
Dependency Injection (DI) framework in ASP.NET is responsible for creating your IndexModel.
DI creates instances and provides as parameters classes that have been registered to the service provider on startup in ConfigureServices()
What happens on a request, is that
ASP.NET creates your IndexModel by asking the DI for it. This is basically the same as calling services.GetService<IndexModel>(). Your pagemodels have been registered to the DI container automatically for you
Whatever arguments your IndexModel constructor has (there can be as many as you need), will get filled in by the DI as long as they have been registered. If there are any non-registered types as arguments, an exception is thrown
In this case, if the code you listed works you have a line registering RazorPagesMovieContext somewhere on ConfigureServices().
Read more about DI in asp.net core: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2
Note the section about service lifetimes as well.
Related
I am struggling with finding a way to register log4net ILog within IServiceCollection services (.NET Core 2.1).
log4net LogManager provides a method that takes a Type as parameter so that it can be used when logging events. Here is an example call:
var log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
However when registering it with services at Startup method, I can use factory resolver, but still the type will be always the same. See the following excerpt:
private void SetServices(IServiceCollection services)
{
services.AddTransient(svc => CreateLog(MethodBase.GetCurrentMethod().DeclaringType)).;
}
protected ILog CreateLog(Type type)
{
return LogManager.GetLogger(type);
}
I was expecting that svc (IServiceProvider) will expose some ways to get to the type being actually resolved but there doesn't seem to be anything.
Also using reflection won't help (IMO, but I could be wrong) because ILog is activated prior to calling the resolved type ctor.
But maybe there is any extension on either MS side or log4net that would help resolving a named logger as explained on the beginning?
This is all to avoid having static members of ILog in any class that uses logging facility and use dependency injection instead.
Thanks, Radek
The way to do it is to implement and then register your own strongly typed Logger class that derives from ILogger.
.Net Core allows from to register generic type interface implementation with no type specified. In this case it would be:
services.Add(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(MyLogging.Logger<>)));
This allows all classes that require logging to use constructor injection as follows:
class A
{
public A(Ilogger<A> logger) {...}
}
Implementation of ILogger which a wrapper to log4net should be rather simple. Please let me know if you need an example.
Radek
I have a ASP .Net Web API controller that I want to take 2 parameters. The first one is an EF context and the second being a caching interface. If I just have the EF context the constructor gets called, but when I add the caching interface I get the error:
An error occurred when trying to create a controller of type
'MyV1Controller'. Make sure that the controller has a
parameterless public constructor.
private MyEntities dbContext;
private IAppCache cache;
public MyV1Controller(MyEntities ctx, IAppCache _cache)
{
dbContext = ctx;
cache = _cache;
}
My UnityConfig.cs
public static void RegisterTypes(IUnityContainer container)
{
// TODO: Register your types here
container.RegisterType<MyEntities, MyEntities>();
container.RegisterType<IAppCache, CachingService>();
}
I would expect that Entity now knows about both types when a request is made for MyV1Controller function it should be able to instantiate an instance since that constructor takes types it knows about but that's not the case. Any idea why?
[EDIT]
Note that I created my own class (IConfig) and registered it and add it to the constructor and it worked, but whenever I try to add the IAppCache to my constructor and make a request to the API I get the error telling me it can't construct my controller class. The only difference that I see is the IAppCache isn't in my projects namespace because it's a 3rd party class but that shouldn't matter from what I understand.
Here are the constructors for CachingService
public CachingService() : this(MemoryCache.Default) { }
public CachingService(ObjectCache cache) {
if (cache == null) throw new ArgumentNullException(nameof(cache));
ObjectCache = cache;
DefaultCacheDuration = 60*20;
}
Check the IAppCacheimplementation CachingService to make sure that the class is not throwing any exception when initialized. that parameterless exception is the default message when an error occurs while trying to create controllers. It is not a very useful exception as it does not accurately indicate what the true error was that occurred.
You mention that it is a 3rd party interface/class. It could be requesting a dependency that the container does not know about.
Referencing Unity Framework IoC with default constructor
Unity is calling the constructor with the most parameters which in this case is...
public CachingService(ObjectCache cache) { ... }
As the container know nothing about ObjectCache it will pass in null which according to the code in the constructor will throw an exception.
UPDATE:
Adding this from comments as it can prove useful to others.
container.RegisterType<IAppCache, CachingService>(new InjectionConstructor(MemoryCache.Default));
Reference here Register Constructors and Parameters for more details.
Most of the DI containers while trying to resolve a type always look for a constructor with maximum number of parameters. That is the reason why CachingService(ObjectCache cache) constructor was being invoked by default. As ObjectCache instance is not registered with Unity, so the resolution fails. Once you force the type registration to invoke specific constructor, everything works.
So if you register IAppCache and force it to invoke CachingService() - parameter less constructor, it will work as expected.
container.RegisterType<IAppCache, CachingService>(new InjectionConstructor());
Registering it this way, will force the parameter less constructor to be invoked and internally it will fall back on whatever the third part library wants to use as default. In your case it will be
CachingService() : this(MemoryCache.Default)
Another option that was mentioned in other answers is to register and pass the constructor parameter your self.
container.RegisterType<IAppCache, CachingService>(new InjectionConstructor(MemoryCache.Default));
This will also work, but here you are taking the responsibility of supplying the cache provider. In my opinion, I would rather let the third party library handle its own defaults instead of me as a consumer taking over that responsibility.
Please take a look at How does Unity.Resolve know which constructor to use?
And few additional information for Niject
https://github.com/ninject/ninject/wiki/Injection-Patterns
If no constructors have an [Inject] attribute, Ninject will select the
one with the most parameters that Ninject understands how to resolve.
For LazyCache version 2.1.2 (maybe even earlier) the existing solution no longer works (no constructor that receives MemoryCache), but it works as simple as:
container.RegisterType<IAppCache, CachingService>(new InjectionConstructor());
This worked with .NET Framework 4.6.1, Unity Abstractions 3.1.0.
Is good idea to get user identity in ASP.NET Web API controller constructor, for example:
public PagesController(PageValidator pageValidator, PageMapper pageMapper, PagesManager pagesManager, UsersManager usersManager)
:base(usersManager)
{
_pageValidator = pageValidator;
_pageMapper = pageMapper;
_pagesManager = pagesManager;
if (User.Identity.IsAuthenticated)
_pagesManager.UserId = usersManager.GetByEmail(User.Identity.Name).Id;
}
Is always User.Identity was correct populated before this call raise?
This has bitten me a few times. Depending on where/how you are performing your authentication, you need to be careful where you access your identity, particularly in controller constructors.
For example, whilst the controller action is invoked AFTER an IAuthenticationFilter is instantiated, the controller's constructor is called before AuthenticateAsync; meaning any authentication you do in AuthenticateAsync will not be available in your controller's constructor (like in your example).
I typically don't rely on things being available during controller construction (unless handled by DI). Instead access the identity as you need it in your controller actions.
If you are looking at making identity lookup easier (i.e. pulling in your user object based on the User.Identity.Name property) create a base controller class that has a property or method that does it for you, then have your controllers inherit from that...
public User AuthenticatedUser
{
get
{
if (User.Identity.IsAuthenticated)
{
return usersManager.GetByEmail(User.Identity.Name);
}
return null;
}
}
EDIT
See here for a detailed breakdown of the Web.API lifecycle, showing controller creation occurring prior to authentication.
Yes. You can use this property in Controller in any place. ASP.NET has request pipeline: (http://www.dotnetcurry.com/aspnet/888/aspnet-webapi-message-lifecycle).
As you can see Authorization is early stage step in request pipeline.
Controller creation is the latest stage.
What should be the Autofac 3.5 configuration for Asp.net Mvc 5.2, SignalR 2.1, MS Owin (Katana) 3.0? Is there less complex way to register Autofac resolvers (there is two of them now)? Or why ILifetimeScope is not visible for my hub?
The exception:
Autofac.Core.DependencyResolutionException: An exception was thrown
while invoking the constructor 'Void .ctor(Autofac.ILifetimeScope)' on
type 'OperatorHub'. --->
No scope with a Tag matching
'AutofacWebRequest' is visible from the scope in which the instance
was requested. This generally indicates that a component registered as
per-HTTP request is being requested by a SingleInstance() component
(or a similar scenario.) Under the web integration always request
dependencies from the DependencyResolver.Current or
ILifetimeScopeProvider.RequestLifetime, never from the container
itself. (See inner exception for details.) --->
Autofac.Core.DependencyResolutionException: No scope with a Tag
matching 'AutofacWebRequest' is visible from the scope in which the
instance was requested. This generally indicates that a component
registered as per-HTTP request is being requested by a
SingleInstance() component (or a similar scenario.) Under the web
integration always request dependencies from the
DependencyResolver.Current or ILifetimeScopeProvider.RequestLifetime,
never from the container itself.
In my OwinStartup (see autofac + mvc owin and autofac + signalr in owin):
public void Configuration(IAppBuilder app)
{
var builder = new ContainerBuilder();
// ... registration. There is .InstancePerRequest() and .SingleInstance()
Autofac.Integration.Mvc.RegistrationExtensions.RegisterControllers(builder,typeof(MvcApplication).Assembly);
Autofac.Integration.SignalR.RegistrationExtensions.RegisterHubs(builder, Assembly.GetExecutingAssembly());
var container = builder.Build();
// 1st resolver
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
app.UseAutofacMiddleware(container);
app.UseAutofacMvc();
// yet the 2nd resolver!
app.MapSignalR(new HubConfiguration { Resolver = new Autofac.Integration.SignalR.AutofacDependencyResolver(container) });
}
The hub:
public class OperatorHub : Hub
{
public OperatorHub(ILifetimeScope hubLifetimeScope)
{
hubLifetimeScope.BeginLifetimeScope();
// ...
// HERE IT FALLS. The IMyService relates to MyDbContext (see below)
var myservice = hubLifetimeScope.Resolve<IMyService>();
}
}
UPDATE
The breaking component registration (EF Context:
builder.RegisterType<MyDbContext>().AsSelf().As<DbContext>().InstancePerRequest("OwinLifetimeScope");
In short the bug is the MyDbContext is not in the 'root' lifetime scope which is passed to OperatorHub constructor.
UPDATE 2
The solution with the help of #TravisIllig is to register the MyDbContext service using .InstancePerLifetimeScope() and to create the one in the hub. Another lifetime scope would be created for http request in asp mvc. Create help at Sharing Dependencies Across Apps Without Requests.
Also the hub should not dispose the given scope as it is the root one which results in ObjectDisposedException on the second run.
There is an FAQ on handling this exact exception on the Autofac doc site. The problem stems from the fact you're using InstancePerRequest in conjunction with SignalR, which, also per the documentation:
Due to SignalR internals, there is no support in SignalR for per-request lifetime dependencies.
You do appear to have looked at the Autofac SignalR docs as I see you've injected a lifetime scope to help you manage instance lifetimes, but that doesn't give you per-request lifetime scopes, it just gives you a hub lifetime scope. I might suggest revisiting that doc for a refresher.
The FAQ I mentioned, in conjunction with the SignalR integration docs, should point you to the right solution for your app. Many people simply switch their registrations from InstancePerRequest to InstancePerLifetimeScope but I strongly encourage you to read the FAQ and check out your options before just jumping to that decision. It may be the right choice, but it may not be - it depends on how your app works internally.
I'm creating an ASP.NET Web API 2.1 site and as I want to inject dependencies directly into the controllers, I've created my own implementation of IDependencyResolver so that StructureMap will handle that for me.
public class StructureMapDependencyResolver : IDependencyResolver
{
public IDependencyScope BeginScope()
{
return this;
}
public object GetService(Type serviceType)
{
return ObjectFactory.GetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return ObjectFactory.GetAllInstances(serviceType).Cast<object>();
}
public void Dispose()
{
}
}
I've then told Web API to use this class by adding this line to the Application_Start method in Global.asax
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver();
That compiled but when I tried to access any of the API methods in a browser I got an error like this
No Default Instance defined for PluginFamily System.Web.Http.Hosting.IHostBufferPolicySelector, System.Web.Http
That one was relatively easy to solve as I added a line to my StructureMap configuration
this.For<IHostBufferPolicySelector>().Use<WebHostBufferPolicySelector>();
However then I got other similar errors for other System.Web.Http classes and while I could resolve some of them I am stuck on how to deal with 3 of them, namely ITraceManager, IExceptionHandler and IContentNegotiator.
The issue is that TraceManager which seems to be the default implementation of ITraceManager is an internal class and so I can't reference it in my StructureMap configuration.
So am I going about this completely the wrong way or is there some other way to inject these internal classes?
I'd like to give you a suggestion and explanation why not to go this way, and how to do it differently (I'd even say better and properly).
The full and complete explanation of the inappropriate IDependencyResolver design could be found here: Dependency Injection and Lifetime Management with ASP.NET Web API by Mark Seemann
Let me cite these essential parts:
The problem with IDependencyResolver
The main problem with IDependencyResolver is that it's essentially a Service Locator. There are many problems with the Service Locator anti-pattern, but most of them I've already described elsewhere on this blog (and in my book). One disadvantage of Service Locator that I haven't yet written so much about is that within each call to GetService there's no context at all. This is a general problem with the Service Locator anti-pattern, not just with IDependencyResolver.
And also:
...dependency graph need to know something about the context. What was the request URL? What was the base address (host name etc.) requested? How can you share dependency instances within a single request? To answer such questions, you must know about the context, and IDependencyResolver doesn't provide this information.
In short, IDependencyResolver isn't the right hook to compose dependency graphs. **Fortunately, the ASP.NET Web API has a better extensibility point for this purpose. **
ServiceActivator
So, the answer in this scenario would be the ServiceActivator. Please take a look at this answer:
WebAPI + APIController with structureMap
An example of the ServiceActivator:
public class ServiceActivator : IHttpControllerActivator
{
public ServiceActivator(HttpConfiguration configuration) {}
public IHttpController Create(HttpRequestMessage request
, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
var controller = ObjectFactory.GetInstance(controllerType) as IHttpController;
return controller;
}
}
All we can do with StructureMap, is in place. The key features of the Web API framework are still in place... we do not have to hack them. And we are also rather using DI/IoC then Service locator
Just try using UnityHierarchicalDependencyResolver instead of the other one. It worked for me. This is for future reference if somebody would like to use Unity