How to initialize and use Custom / Support classes in MVC 6 with Asp.Net Core 2.0 - class

public sealed class SessionContext
{
private ISession httpContext;
public SessionContext(ISession httpContext)
{
this.httpContext = httpContext;
}
public string UserType
{
get
{
return httpContext.GetString("_UserType");
}
set
{
httpContext.SetString("_UserType", value);
}
}
...... More properties .....
}
public class HomeController : Controller
{
private AppSettings _appSettings;
private SessionContext session = null;
private readonly IHttpContextAccessor _httpContextAccessor;
private ISession httpContext => _httpContextAccessor.HttpContext.Session;
//I don't like this constructor as it is getting initialize or every controller call.
public HomeController(IOptions<AppSettings> myAppSettings, IHttpContextAccessor httpContextAccessor)
{
_appSettings = myAppSettings.Value;
_httpContextAccessor = httpContextAccessor;
appSettings = new AppSettings(_appSettings); //Should initialize only once.
session = new SessionContext(httpContext);
}
}
I have questions regarding ...
How to initialize and use Custom / Support classes in MVC 6 with Asp.Net Core 2.0
When I Initialize these classes, they getting initialize or every controller call. That is very redundant.
my SessionContext class is getting re-initialize every time. So I am loosing the values when I call this class from another controller.
I tried this approach but, not much of use.
services.AddSingleton();

Move from question to answer:
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddSingleton<SessionContext, SessionContext>();
//calling the extension class to instantiate the classes which we require earlier.
services.AddMyProjectHelper(Configuration)
}
Created a extension class... where it initializes the support classes
public static class MyProjectHelperExtensions
{
public static IServiceCollection AddMyProjectHelper(this IServiceCollection services, IConfiguration configuration)
{
var section = configuration.GetSection("AppSettings");
// we first need to create an instance
var settings = new AppSettings();
// then we set the properties
new ConfigureFromConfigurationOptions<AppSettings>(section).Configure(settings);
var session = services.BuildServiceProvider().GetService<SessionContext>();
// then we register the instance into the services collection
services.AddSingleton<MyProjectHelper>(new MyProjectHelper(settings, session));
return services;
}
}
finally controller ctor uses the DI for the required class. Now I have avoided redundant initialization of support classes.
public SecurityController(MyProjectHelper objHelper, SessionContext sessionContext)
{
session = sessionContext;
projectHelper = projectHelper ?? objHelper;
}
Now, I am able to share the session variables which I have set in my support classes
private SessionContext session = null;
public HomeController(SessionContext sessionContext)
{
session = sessionContext;
}
[Authorize]
public IActionResult Index()
{
if (session.CurrEmployee != null)
{
ViewBag.Name = (session.CurrEmployee.FirstName + " " + session.CurrEmployee.LastName);
return View();
}
}

Related

Databasecontext gets disposed - Custom (nested) service(s)

I try to inject my DbContext using services.AddDbContext in my Startup.cs. It's gets injected in the service that needs to handle every call to the DB. This AzureService gets injected in other services that actually need the data. When I try this however I always get a system.ObjectDiposedException on de DbContext inside AzureService.
When I inject it directly in the CompareService it just work, so I'm probably making a grave mistake with the nested services. Help/insights much appreciated.
code:
Startup.cs
services.AddDbContext<SchoolDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SchoolSyncDb")));
services.AddScoped<IAzureService, AzureService>();
services.AddScoped<ICompareService, CompareService>();
AzureService
public class AzureService : IAzureService
{
private SchoolDbContext schoolDbContext;
private IMapper mapper;
private IHelperService helperSrv;
public AzureService(SchoolDbContext _sdb, IMapper _mapper, IHelperService _helper)
{
schoolDbContext = _sdb;
mapper = _mapper;
helperSrv = _helper;
}
CompareService
public class CompareService: ICompareService
{
private readonly IWisaService wisaSrv;
private readonly ISmartschoolService smtSrv;
private readonly IAzureService azureSrv;
private readonly IHelperService helperSrv;
private readonly ILoggerService loggerSrv;
public CompareService(IWisaService _ws, ILoggerService _ls, ISmartschoolService _ss, IAzureService _as, IHelperService _hs)
{
wisaSrv = _ws;
smtSrv = _ss;
azureSrv = _as;
helperSrv = _hs;
loggerSrv = _ls;
}
trying to get data from the AzureService in the CompareService fails because the DbContext in the AzureService is Diposed.
List<AdbStudentModels> DbList;
try
{
DbList = azureSrv.GetAllStudentInDbBySchool(school);
}
In AzureService
public List<AdbStudentModels> GetAllStudentInDbBySchool(string school)
{
try
{
return schoolDbContext.AdbStudentModels.Where(i => i.School.Schoolnaam.Equals(school)).ToList();
}
catch (Exception ex)
{
throw ex;
}
}
It's seems that I've found a solution reading this article. I changed the lifecycle for CompareService to singleton and the one from AzureService to transient.
I still inject AzureService into CompareService but instead of injecting the DbContext into the azureService, I inject IServiceprovider as a whole and create a scope for the DbContext.
I am by no means a professional programmer, so I'm not claiming this to be the solution or the way to implement this correctly. It just does what I need at the moment.
Startup.cs
services.AddDbContext<SchoolDbContext>(options => options.UseSqlServer(connString));
services.AddTransient<IAzureService, AzureService>();
services.AddSingleton<ICompareService, CompareService>();
CompareService
private readonly IAzureService azureSrv;
public CompareService(IAzureService _as)
{
azureSrv = _as;
}
AzureService
private IServiceProvider sp;
public AzureService(IServiceProvider _sp)
{
sp = _sp;
}
Method in AzureService needing the DbContext (using scope)
public List<AdbStudentModels> GetAllStudentInDbBySchool(string school)
{
try
{
using (var scope = sp.CreateScope())
{
SchoolDbContext db = scope.ServiceProvider.GetRequiredService<SchoolDbContext>();
return db.AdbStudentModels.Where(i => i.School.Schoolnaam.Equals(school)).ToList();
}
}
catch (Exception ex)
{
throw new Exception("GetAllStudentInDbBySchool" + " / " + ex);
}
}

How do I resolve a WebAPI dependency in Autofac that requires a parameter from the route?

I am struggling with wiring dependencies through autofac in my WebApi 2 project. I have a following interface and class that i'd like to inject in my GET and POST controller actions,
public interface IRepository
{
IContext Context
{
get;
}
void SomeOperation();
}
public MyRepository : IRepository
{
IContext _context;
public MyRepository(IContext context)
{
_context = context;
}
public Context
{
get
{
return _context;
}
}
public void SomeOperation
{
// Perform some operation using _context;
}
}
I 'd like IRepository to be injected in controller like this,
public class MyController : ApiController
{
private readonly IRepository _repo;
public ApplicationsController(IRepository repo)
{
_repo = repo;
}
// GET: api/v1/Contexts({contextId})
public IHttpActionResult Get(string contextId)
{
_repo.SomeOperation();
}
}
IContext object to be injected in MyRepository has to be fetched from a factory, something like this
public class ContextFactory
{
Hashtable contextMap;
IContext Get(string contextId)
{
if contextMap.Contains(contextId)
return contextMap[contextId].Value;
else
{
IContextConfiguration configuration = ContextConfigurationFactory.Get(contextId);
IContext context = new ConcreteContext(configuration);
contextMap.Add[contextId, context];
return context;
}
}
}
I am not sure how to wire all the classes and convert logic in factory classes by injecting relationships through Autofac so that context id passed in url is passed to ContextConfigurationFactory.Get and instantiate ConcreteContext object when not found in hash and eventually Autofac injecting right context object in MyRepository before passing it on to Get action in the controller.
Let's simplify this a bit. What you're trying to do is:
Get the context ID from a route parameter.
Use that route parameter in the factory to create a context.
The rest seems pretty much peripheral - the repository, the controller, all that. The crux of the question is that you need to get a route parameter into your factory.
Given that, let's put together some simplified code:
public class ContextFactory
{
public IContext Get(string contextId)
{
return new Context(contextId);
}
}
public interface IContext
{
string Id { get; }
}
public class Context : IContext
{
public Context(string id)
{
this.Id = id;
}
public string Id { get; private set; }
}
That's basically what you have:
An IContext interface that things need.
A ContextFactory that is basically responsible for building these things.
A Context concrete implementation of IContext that is built by the factory.
I would probably do something like this:
var builder = new ContainerBuilder();
builder.RegisterType<ContextFactory>();
builder.Register(ctx =>
{
var routeData = HttpContext.Current.Request.RequestContext.RouteData;
var id = routeData.Values["contextId"] as string;
var factory = ctx.Resolve<ContextFactory>();
return factory.Get(id);
}).As<IContext>()
.InstancePerLifetimeScope();
Now when you resolve IContext it will use your factory, get the current context ID from route data, and pass it through the factory.
I will leave the following for you to look into:
What happens if the route parameter isn't there? (Autofac won't let you return null.)
What happens if the route parameter has invalid data?
The route parameter is pretty hackable, is this a security risk?
...and so on.

How can I achieve the following using IOC?

I want to use IOC with my service and I want to instead inject a class not an interface in the constructor as below in the services layer but I do not want to create a new object from the calling layer like var service = new InvoiceService(new ChangeInvoiceDueDateCommand()) instead I want to create something like this from my controller in MVC where the IInvoiceService is injected into the controller constructor but the problem I see is that
public InvoiceController(IInvoiceService invoiceService, IMapper mapper)
{
_invoiceService = invoiceService;
_mapper = mapper;
}
and then called like this
public ActionResult ChangeInvoiceDueDate(InvoiceChangeDueDateViewModel invoiceChangeDueDateViewModel )
{
var request = _mapper.Map<InvoiceChangeDueDateViewModel, ChangeInvoiceDuedateRequest>(invoiceChangeDueDateViewModel);
InvoiceChangeDueDateResponse response = _invoiceService.ChangeDueDate(request);
return View();
}
Service Layer
public class InvoiceService : IInvoiceService
{
private readonly ChangeInvoiceDueDateCommand _changeInvoiceDueDateCommand;
public InvoiceService(ChangeInvoiceDueDateCommand changeInvoiceDueDateCommand)
{
_changeInvoiceDueDateCommand = changeInvoiceDueDateCommand;
}
public InvoiceChangeDueDateResponse ChangeDueDate(ChangeInvoiceDuedateRequest invoiceChangeDueDateRequest)
{
_changeInvoiceDueDateCommand.Execute(invoiceChangeDueDateRequest);
return new InvoiceChangeDueDateResponse {Status = new Status()};
}
}
Command
public class ChangeInvoiceDueDateCommand : ICommand<ChangeInvoiceDuedateRequest>
{
private readonly IRepository<Invoice> _invoiceRepository;
readonly InvoiceDueDateChangeValidator _validator;
public ChangeInvoiceDueDateCommand(IRepository<Invoice> invoiceRepository)
{
_invoiceRepository = invoiceRepository;
_validator = new InvoiceDueDateChangeValidator();
}
public void Execute(ChangeInvoiceDuedateRequest request)
{
if (_validator.IsDuedateValid(request.NewDuedate))
{
Invoice invoice = _invoiceRepository.GetById(request.Id);
invoice.ChangedDueDate(request.NewDuedate);
_invoiceRepository.SaveOrUpdate(invoice);
}
else
{
throw new InvalidDueDateException();
}
}
}
ICommand
public interface ICommand<T> where T : IRequest
{
void Execute(T request);
}
IRequest
public interface IRequest
{
int Id { get; set; }
}
I worked it out. It was just a Windsor syntax issue. It ended up being as simple as registering the Command using the container.Register(Component.For<ChangeInvoiceDueDateCommand>());

Passing connection string to Entity framework at runt time for each call

My Entity framework context is as following
public partial class MyContext : DbContext, IMyContext
{
static MyContext()
{
System.Data.Entity.Database.SetInitializer<MyContext>(null);
}
public MyContext()
: base("Name=MyContext")
{
}
I am resolving it through autofac in the following way
builder.RegisterType(typeof(MainContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType<MainContext>().As<IMainContext>().InstancePerRequest();
This db context gets called in repository layer
#region Fields
private readonly IMyContext _context;
#endregion
#region Constructors and Destructors
public EmployeeRepository(IMyContext context)
{
_context = context;
}
#endregion
public void Create(Employee emp)
{
this._context.Employee.Add(emp);
}
Now my issue is , I want to set the connection string dynamically per call. The connection string will be passed through a webapi which i want to pass on to this context. Can anyone help me how can i do that? I am confused about autofac here. Secondly how can i make sure each call sets connection string and does not cache it.
You can use a factory that will build the context and set the connectionstring for you.
public interface IContextFactory
{
IContext GetInstance();
}
public class MyContextFactory : IContextFactory
{
public IContext GetInstance()
{
String connectionString = this.GetConnectionString(HttpContext.Current);
return new MyContext(connectionString);
}
private String GetConnectionString(HttpContext context)
{
// do what you want
}
}
builder.RegisterType<MyContextFactory>()
.As<IContextFactory>()
.InstancePerRequest();
builder.Register(c => c.Resolve<IContextFactory>().GetInstance())
.As<IContext>()
.InstancePerRequest();
If you can't get connectionstring based on HttpContext, you can change contextFactory implementation to expect initialization by WebAPI before creating the instance. For example :
public interface IContextFactory
{
IContext GetInstance();
void Initialize(String connectionString);
}
public class MyContextFactory : IContextFactory
{
private String _connectionString;
public void Initialize(String connectionString)
{
this._connectionString = connectionString;
}
public IContext GetInstance()
{
if (this._connectionString == null)
{
throw new Exception("connectionString not initialized");
}
return new MyContext(this._connectionString);
}
}
At the beginning of your web API call (through attribute for example), you can call the Initialize method. Because the factory is InstancePerRequest you will have one instance for the duration of the request.
By the way, I'm not sure to understand this registration
builder.RegisterType(typeof(MainContext)).As(typeof(DbContext)).InstancePerLifetimeScope();
builder.RegisterType<MainContext>().As<IMainContext>().InstancePerRequest();
It looks buggy because you will have 2 different registration of the same type and not for the same scope, is it intended ? Furthermore, it doesn't sound a good idea to register a DbContext, do you need this registration ?
The following registration looks better :
builder.RegisterType<MainContext>()
.As<IMainContext>()
.As<DbContext>()
.InstancePerRequest();

Why does my sub-dependency not get set in Dagger?

I am having a hard time figuring out how to inject CachedRithms into my RithmioManager and CachedKamms into my KamilManager?
I have the following files:
AppScopeModule:
#Module
(
library = true,
complete = false,
injects = {
KamilApplication.class,
KamilManager.class
}
)
public class AppScopeModule {
/* package */ static Context sApplicationContext = null;
private final Context mApplicationContext;
AppScopeModule(Context applicationContext) {
KamilManager.initInstance(applicationContext);
mApplicationContext = applicationContext;
}
#Provides
#Singleton
KamilManager provideKamilManager() {
return KamilManager.getInstance();
}
}
KamilApplication:
public class KamilApplication extends Application implements Injector {
private ObjectGraph mObjectGraph;
#Inject
KamilManager KamilManager;
#Override
public void onCreate() {
super.onCreate();
AppScopeModule sharedAppModule = new AppScopeModule(this);
// bootstrap. So that it allows no-arg constructor in AppScopeModule
sharedAppModule.sApplicationContext = this.getApplicationContext();
List<Object> modules = new ArrayList<Object>();
modules.add(sharedAppModule);
modules.add(new AuthModule());
modules.addAll(getAppModules());
mObjectGraph = ObjectGraph.create(modules.toArray());
mObjectGraph.inject(this);
}
}
KamilManager
public class KamilManager {
#Inject
CachedKamms mCachedKamms;
private static KamilManager instance;
private boolean mWearIsConnectedToMobile;
private KamilManager() {
Log.d(TAG, "KamilManager private constructor");
}
public static void initInstance(Context appContext) {
if (instance == null) {
instance = new KamilManager();
.....doing more things here...
}
}
public static KamilManager getInstance() {
return instance;
}
}
But mCAchedKamms is always blank when I initialize the app. Any idea what I'm doing wrong?
You need to call ObjectGraph.inject(this) somewhere in KamilManager.
I suggest you to add this code to your KamilApplication class:
public ObjectGraph getObjectGraph() {
return mObjectGraph;
}
After that you need to somehow get instance of KamilApplication(pass it via constructor maybe?) in KamilManager and call:
kamilApplication.getObjectGraph.inject(this);
after this call every field in class KamilManager annotated with #Inject should be injected.
OR
Just annotate constructor of CachedKamms with #Inject
Extra:
Avoid of using library = true and complete = false unless you know what are you doing. With this settings you disable some validations at compile time.