I am trying to generate a generic BaseViewPage in asp.net Core to access Current User's Identities.
For this purpose I created a BaseViewPage.cs file -
public abstract class BaseViewPage<TModel> : RazorPage<TModel>
{
private static ClaimsPrincipal principal;
public BaseViewPage(IPrincipal _principal)
{
principal = _principal as ClaimsPrincipal;
}
}
As you can see in the constructor here I am injecting a dependency of IPrincipal
type so that it gets defined at run time.
Now time to inherit it in _viewimports.cshtml file to use current user in all the view pages as below -
@using TWCStore
@inherits MyStore.Helpers.BaseViewPage<TModel>
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
Whenever I try to use any property in my view - ProductCategories.cshtml
the error invokes here
Severity Code Description Project File Line Suppression State Error CS7036 There is no argument given that corresponds to the required formal parameter '_principal' of 'BaseViewPage.BaseViewPage(IPrincipal)' MyStore D:\Projects\TWCStore\TWCStore\Views\Store\ProductCategories.cshtml 1 Active
I am assuming when I am injecting the dependency then it wants me to put the IPrincipal
as Dependency here too -
@inherits MyStore.Helpers.BaseViewPage<TModel>
How do I inject this dependency in here ?
Its late I am writing solution (actually an alternate) to this problem here.
So I followed dependency injection (sorry for now forgetting the help link).
Here is what I did -
Create an Interface
public interface IAppUserAccessor
{
int MemberId { get; }
}
Resolver class
public class AppUserAccessor : IAppUserAccessor
{
private readonly MyContext _context;
public AppUserAccessor(MyContext context)
{
_context = context;
}
int IAppUserAccessor.MemberId
{
get
{
return _context.Member.MemberId;
}
}
}
Register the service in StartUp.cs under 'ConfigureServices' section
services.AddTransient<IAppUserAccessor, AppUserAccessor>();
Inject in _viewimports.cshtml
@using MyApplication
@inject MyApplication.Helpers.IAppUserAccessor AppUserAccessor
Now this is accessible in every view as -
@AppUserAccessor.MemberId