ASP.NET Core MVC application dependency injection issue when using BaseController - asp.net

Recently i tried to create a MVC application using ASP.NET Core 2.0 and i had some values defined in appsettings.json,
"MySettings": {
"WebApiBaseUrl": "http://localhost:6846/api/"
}
In order to read these values i have added
services.Configure<MySettingsModel>(Configuration.GetSection("MySettings"));
above line in ConfigureServices method in Startup.cs
and in my home controller i have added
private readonly IOptions<MySettingsModel> appSettings;
public HomeController(IOptions<MySettingsModel> app)
{
appSettings = app;
}
MySettingsModel class is just a model with property same as key define in appsettings.json.
by this method i'm able to read the value of this key.
Now my issue is that i want to use this key in many controllers so i don't want to repeat this code in every controller so what i did was i created a BaseConntroller, added its constructor and i got my values there. But when i inherit other controllers with my BaseController , it throws me an error and tells me to generate it's constructor, so basically it tells me to add constructor in every controller which is what i wanted to avoid.
How can i achieve this?
You can see the image for the error
And these are the potential fixes that it shows me.

This is just basic C# inheritance. Derived classes must re-implement constructors on base classes (at least the ones you want or need). The only exception is the empty constructor, which is implicit. In other words, you simply need:
public class HomeController : BaseController
{
public HomeController(IOptions<MySettingsModel> app)
: base(app)
{
}
And, of course, you need to change the accessibility of the base class field to protected instead of private. Otherwise, derived classes will not be able to access it.
Of course, this doesn't really save you that much. However, there's no free lunch here. Like I said, this is a limitation of C#, itself, so you have no choice. Although, it's worth mentioning, that while this can sometimes be annoying, it's actually a kind of useful feature of C#. You can look at any class and see exactly what constructors it has available, without having to trace down all its ancestors.

Actually, there is a good solution here:
https://stackoverflow.com/a/48886242/2060975
I am mostly using this method.
[Authorize]
[ApiController]
public abstract class ApiControllerBase : ControllerBase
{
private IOptions<AppSettings> _appSettings;
protected IOptions<AppSettings> appSettings => _appSettings ?? (_appSettings = (IOptions<AppSettings>)this.HttpContext.RequestServices.GetService(typeof(IOptions<AppSettings>)));
...
}
I hope it helps someone:)

Related

Why are OWIN startup classes declared as partial, yet sometimes not?

If I use VS2015.1 to create a new sample project (either WebForms or MVC), two files are created for configuring OWIN:
\Startup.cs (or .vb)
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(WebApplication6.Startup))]
namespace WebApplication6
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}
\App_Start\Config.Auth.cs (or .vb)
namespace WebApplication6
{
public partial class Startup {
public void ConfigureAuth(IAppBuilder app)
{
// removed for brevity
}
}
}
I see that both classes are declared as partial, but in the many examples online of how to use OWIN, the classes are not partial (see here, here, here and here).
Could anyone please explain if there is a correct or best approach, and what difference it makes to the application whether partial is used or not?
The accepted answer is true if and only if the code generator is generating the file each and every time a build happens. The example with OWIN does not qualify since both files are generated only once when the framework / scaffolding choices are made.
Therefore the only reason I can see that the startup is generated as a partial class is that the framework developers did not want to couple the generation of the owin authorization (a cross cutting concern) with the generation of the startup scaffolding; however, they were only successful in removing the clutter from the base startup.cs scaffolding and were not able to decouple it since they had to introduce the OwinStartupAttribute to the base start up and make a call to the method introduced in the new partial class ConfigureAuth. This is actually a perfect example of how not to use a partial class. Partial class definitions should be decoupled otherwise the benefit gained by using partial class is outweighed by the indirection it creates. Having to modify the base partial class definition to add another partial class to add the OWIN authorization makes it clear to me that this is a flawed approach.
I think I found an answer here, but would still appreciate anything others can add in the context of OWIN specifically:
https://stackoverflow.com/a/3601918/792888
The biggest use of partial classes is make life easier on code
generators / designers. Partial classes allow the generator to simply
emit the code they need to emit and do not have to deal with user
edits to the file. Users are likewise free to annotate the class with
new members by having a second partial class. This provides a very
clean framework for separation of concerns.
So the partial class is simply compiled into a class. The partial declaration allows other classes with the same name to co-exist (which are then all compiled together into a single class).

asp.net MVC : use unitOfWork inside custom AuthenticationAttribute when ActionFilters are not per-request?

I have implemented IAuthenticationFilter to create a custom one. in the constructor I use structureMap to get instance of my IUnitOfWork. this authentication logic is to check user status in the database and ....
IUnitOfWork uow;
public CustomAuthenticatationAttribute()
{
this.uow = ObjectFactory.GetInstance<IUnitOfWork>();
}
I have configured structureMap to serve IUnitOfWork HttpContextScoped.
x.For<IUnitOfWork>().HttpContextScoped().Use(() => new MyDbContext());
but then something strange happened. I deleted the user in one action, but when the AuthenticationFilter is executed on another action, the instance of unitOfWork still returns the user ! I searched the web for hours and I come to this :
Are ActionFilterAttributes reused across threads? How does that work?
in short , it says that Filters are cached and used across requests !
Now I'm confused . how to deal with this ? shall I give up using unitOfWork and get back to using(var context = ....) ? or there is a correct way of using unitOfWork inside Filters .
I found a solution here
https://gist.github.com/ivanra/9019273
It replaces the DefaultFilterProvider and I prefer to avoid that if possible.
The solution you found with suppressing caching in the FilterProvider is actually the same solution that the MVC integration libraries for both Autofac and Simple Injector use.
But the caching behavior of attributes is just one of the many reasons why doing dependency injection in attributes is actually a bad idea.
The best solution is IMO to move to passive attributes if you can, or at least encapsulate the attributes logic and its dependencies into a component and don't do anything more than resolving and executing that component in the OnActionExecuting method. For instance:
public class CustomAuthenticatationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
var action =
ObjectFactory.GetInstance<IActionFilter<CustomAuthenticatationAttribute>>();
action.OnActionExecuting(this, context);
}
}

Add Extension Method to MembershipProvider

I am currently working on a Custom MembershipProvider implementation. But I need additional methods. I would like to call those methods directly on the Membership object within my Controller like this:
Membership.DoStuff()
Is it possible to do that with an extension method? Where would I start?
thanks!
learning more about extension methods is a good start. Please refer to following articles
http://technico.qnownow.com/2012/03/17/how-to-create-extension-methods-in-net/
extension methods (MSDN)
Why don't you add it directly to you class (which have the custom MemebershipProvider) then cast the membership clasd to your then you will find it.
If you asking about the extension methods it should work on any class, so the answer to your question is Yes.
After trying a lot of examples I have found this post where they state that you cannot write extension methods to a static class.
Membership is a static class and you cannot extend it.
yes, Membership is extensible, but you don't extends static class Membership (because it's impossible), you must extends abstract class MembershipProvider, and calls extension methods like Membership.Provider.DoStuff().
For example:
extension class
namespace Infrastructure.Extensions
{
public static class MembershipProviderExtensions
{
public static void DoStuff(this MembershipProvider provider)
{
// do stuff
}
}
}
in your code
using Infrastructure.Extensions;
...
Membership.Provider.DoStuff()
...

Setting up Non-Public Properties using Moq Functional Syntax

Anyone know if the Moq functional syntax supports setups for Non-Public properties? I noticed that it doesn't work.
NOTE: This is for the functional syntax.
public class Foo
{
public virtual int FooProperty { get; protected set; }
}
This doesn't throw an error, but fails to mock FooProperty
Mock.Of<Foo>(x => x.FooProperty == 1);
The regular syntax works fine.
var mockFoo = new Mock<Foo>(); mockFoo.SetupGet(x=>x.FooProperty)
.Returns(1)
It might be worth looking at the Pex/Moles tool from Microsoft Research. Moles is used to create accessors for non-public stuff.
It will support mocking of internal properties if you add an assembly attribute to the assembly containing the class under test (add to AssemblyInfo.cs):
// This assembly is the default dynamic assembly generated Castle DynamicProxy,
// used by Moq. Paste in a single line.
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
(You would also have to add an InternalsVisibleTo entry for your test project, of course.)
If you do this, you can mock any internal property in the assembly to which this is added. If you want to mock private or protected properties, I'm pretty sure there's no way to do that directly. If they're protected, you could create a Dummy inheritor and give it public methods or properties that access/manipulate its protected members. For private, there's really nothing you can do, I believe.

How to use Ninject.Web.PageBase alongside another, custom .NET PageBase

I am trying to get Ninject working with a WebForms application that already has a custom PageBase object. But, I don't know for sure if I can use Ninject's PageBase object alongside another, custom PageBase. I've been searching for a while now to see if I could find an answer to this problem, or to learn how to do it, but all I've found is this:
I've hacked together an alternative using a shared base class that
derives from Page. It looks roughly like this
public abstract class PageBase : Page
{
public IKernel Kernel { get; private set; }
public PageBase() { Kernel = ...; }
public void Page_Init() { Kernel.Inject(this); }
}
This will allow you to property and method injection on any pages that
inherit from PageBase. Note that the constructor is incomplete --
you'll have to access the kernel in some static fashion. You should
be able to read it from the HttpApplication somehow.
(source: http://groups.google.com/group/ninject/browse_thread/thread/317fc48387399aa6, linked from Ninject with ASP.Net webforms and MVC):
This looks like it might work for me because it appears that I could apply this code to the existing, custom PageBase. But, I am hung up on the part in which the author says, "... the constructor is incomplete -- you'll have to access the kernel in some static fashion."
Does anyone have any idea what that sentence means, and how one might go about accessing the Ninject kernel in a static fashion?
You do not need to derive from a Ninject page base. You can alternatively use the NinjectHttpModule.
https://github.com/ninject/ninject.web/blob/master/src/Ninject.Web/NinjectHttpModule.cs

Resources