Configuration(IAppBuilder) not firing on start up - asp.net-mvc

The configuration method below doesn't get fired.
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(SCM.Web.Startup))]
namespace SCM.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder builder) { }
}
}
I've followed all the hints from here and it's a new project, not an upgrade. I can't for my life see how to get it to stop on the breakpoint and I'm in need to get more suggestions on how to troubleshoot it.
It's an intranet application so there's no logging in. The identity gets set to the Windows credentials, instead. I need to assign the roles so that only certain users can access certain actions in the controllers. I'm usually applying OWIN and application cookies, so that's the method I'm trying to follow here, as well.

You need an OwinStartup attribute to tell Owin what method to call. From the docs:
Used to mark which class in an assembly should be used for automatic startup.
Add one to your project, before the namespace declaration:
[assembly: OwinStartup(typeof(Your.Namespace.Startup))]
namespace Your.Namespace
{
public partial class Startup
{
public void Configuration(IAppBuilder builder) { }
}
}
There are some other methods to let Owin know which method (described here) but this is the simplest and probably the most common.

If you are running the website on an external IIS or maybe on the "real" IIS installed on your computer (and not the one that is fired up when you start the run), then it's likely that you're missing the breakpoint because the debugger isn't attached to the process yet when you pass by.
I think that you can confirm it by either checking the settings of your solution and projects or simply adding this code to the method that you don't think that you pass through.
throw new Exception("Killroy was here...");

Related

Where Do I Declare Unity Container?

I'm just getting started with Unity, and I'm having trouble finding any advice about where to declare my UnityContainer object. Most of the examples that I've seen consist of just a single method where the UnityContainer object is declared at the top, then its mappings are defined, then a few object types are resolved. But how do you handle the container when you need to access it in several places throughout the program? For example, the user clicks on a button which opens a new window and that window needs a controller, which itself needs to resolve several services? I also want some of the services that Unity manages to be singletons, so wouldn't that mean that I'd have to have only a single instance of my UnityContainer throughout my program to manage those singletons?
My first thought is to have my main Program class have a static UnityContainer property or expose some sort of UnityContainerFactory class which manages a singleton UnityContainer instance, but both of those methods seem bad because they create a global property which a lot of things are dependent on.
What's the accepted way of doing this?
As noted in the other answer, you should compose the entire object graph in the Composition Root.
Don't declare the container as a static field since this would encourage developers to use it as a service locator which is an anti-pattern.
How to solve your problem?
Use Dependency Injection.
Here is an example for your special WinForms case:
In your Program.Main method, create the container, register the service (the dependency that you need to use from the other window) and then resolve the main form and run it like this:
UnityContainer container = new UnityContainer();
container.RegisterType<IService, Service>();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(container.Resolve<MainForm>());
In the MainForm, declare a dependency on a Func<SecondForm> where SecondForm is the form that you need to create from the main form when the button is clicked. Consider the following code inside your main form file:
public partial class MainForm : Form
{
private readonly Func<SecondForm> m_SecondFormFactory;
public MainForm(Func<SecondForm> second_form_factory)
{
m_SecondFormFactory = second_form_factory;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SecondForm second_form = m_SecondFormFactory();
second_form.Show();
}
}
Please note that Func<SecondForm> acts as some kind of factory. I use it in this case because unity has a feature to support late construction of dependencies via Func.
The SecondForm has a dependency on IService like this:
public partial class SecondForm : Form
{
private readonly IService m_Service;
public SecondForm(IService service)
{
m_Service = sevice;
InitializeComponent();
}
//Use service here
}
You can now use IService from the second form.
Using Seemann words:
As close as possible to the application's entry point.
Give a look at http://blog.ploeh.dk/2011/07/28/CompositionRoot/ from the great Seemann.
I think that is totally acceptable for the main container to be a static field that get disposed together with your application, just remember to don't tie your classes to your container.
Get noticed of the so called "Service Locator" (again from Seemann: http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/)
Where to declare it really depends on the application, I'd go for the startup class of an owin application or the Main method of a console/WPF app.

vNext. AspNet.Identity and custom UserStore. UserStore disposed exception

I'm trying to understand vNext.
I wrote custom UserStore, that works with MongoDB and implements these interfaces:
public class UserStore : IUserStore<ApplicationUser>, IUserPasswordStore<ApplicationUser>, IUserSecurityStampStore<ApplicationUser>,
IUserLoginStore<ApplicationUser>, IUserClaimStore<ApplicationUser>, IUserEmailStore<ApplicationUser>, IUserRoleStore<ApplicationUser>,
IUserTwoFactorStore<ApplicationUser>
In Startup.cs added:
app.UseServices(services =>
{
services.AddIdentity<ApplicationUser>()
.AddUserStore(() => { return new UserStore(); })
.AddUserManager<UserManager<ApplicationUser>>()
.AddHttpSignIn();
services.AddMvc();
});
Then tried to use unchanged AccountController from Visual Studio template and have troubles.
When signing in i getting ObjectDisposedException in UserStore.FindByNameAsync() -- something called UserStore.Dispose().
In UserManager code on github.com/aspnet Store.Dispose() called only in UserManager.Dispose().
I can just ignore calls of Dispose and all works fine, but this is not good way.
So i have no ideas what shall i do
P.S. The Question is: what (and why) can call UserStore.Dispose()?
In vNext, DI is built in and manages the lifetime of the identity services. You are probably trying to use identity after the services have been disposed, by default identity services have lifetimes scoped to a request, so if for example, you are trying to hang onto a reference to a user manager and reuse it across multiple requests, that would cause the ObjectDisposedException.

Use Entity Framework Code First with ASP.NET and Unity Ioc

I got ASP.NET MVC application and I'm using EF code first and Unity dependency injector.
I've implemented the DDD design and have repositories and services which interact with my POCO objects.
My problem is that I'm getting EF related problems - such as the connection was closed, the entities changed or not tracked and so on. As I've understand from researches in Google, it related to the way that I should configure Unity.
I've understood that I need to put it as per request instance, but as I see there's no built-in strategy in Unity nor in the Unity.Mvc3 package.
I've tried to write my own strategy, which solved many problems but I do stuck with the problem that sometimes I get "connection closed".
My HttpContextLifetimeManager.cs
public class HttpContextLifetimeManager<T> : LifetimeManager, IDisposable
{
public override object GetValue()
{
return HttpContext.Current.Items[typeof(T).AssemblyQualifiedName];
}
public override void RemoveValue()
{
HttpContext.Current.Items.Remove(typeof(T).AssemblyQualifiedName);
}
public override void SetValue(object newValue)
{
HttpContext.Current.Items[typeof(T).AssemblyQualifiedName] = newValue;
}
public void Dispose()
{
RemoveValue();
}
}
And inside DependencyConfig.cs (MVC 4 App_Start) I'm registering it using:
container.RegisterInstance<MyDbContext>(new MyDbContext(), new HttpContextLifetimeManager<DependencyConfig>());
Can you recommend me an implementation that works/help me fix mine/forward me to an article or a tutorial that can help me solve that problem?
Thanks a lot.
App_Start method is only called once when the first request comes for the application.
Called when the first resource (such as a page) in an ASP.NET application is requested.
The Application_Start method is called only one time during the life cycle of an application.
See MSDN
Therefore you are creating the one context for all requests. Then after sometimes it may be disposed. And it's not a good practice to keep one DbContext for all the requests (memory issues etc..).
So you can try putting that code in the Application_BeginRequest .

Error Logging in Asp.net mvc app inside web application or domain layer?

I just want to know what would be best practice/ widely used, I currently do my logging in the domain service layer, however anything that happens inside my web application layer is not logged.
I would like one centralized and simple location to do all my create/delete/update loggging...
I have heard of Elmah, not sure how useful it is for domain service layer logging only...
I currently do not use any framework for logging at all, I just string builder my log message or get the exception and flush it into the database... Is this the best way to go about it?
If it matters... I need to use Ninject to inject in my ILoggingService
NOTE: I am not talking about Logging User Activity... that will definetly reside only inside my domain service layer...
Haroon,
Leverage Ninject to create and manage the lifetime of an ILoggingService. The implementation of that service should be built directly on top of a well tested logging library like NLog or log4net.
Once you have an instance of the service, you can easily inject it into either you MVC controller or your domain layer. All logging should happen against that instance, not a static logging class.
This will allow you to have the unified logging you are looking for, with a clean separation of concerns.
imho logging should not be injected. The reason is that most of your services (if not all) will use logging.
If you look at most logging frameworks (like nlog), they are using a singleton/facade and abstract factories to provide logging.
Something like:
public static class LogFactory
{
private static ILogFactory _instance;
public void Assign(ILoggingFactory factory)
{
_instance = factory;
}
public ILogger CreateFor<T>()
{
return _instance.CreateFor<T>();
}
}
The design makes your services only dependent of one class and one interface. Thus it's still extremely easy to switch logging implementations.
In your class use the code like:
public class ServiceImp : IService
{
private ILogger _logger = LogFactory.CreateFor<IService>();
public void SomeMethod()
{
_logger.Warning("Something went wrong, but we can handle it. Hence only a warning");
}
}

ASP.NET MVC Configuration Class using IoC

In an MVC app, we the have need to create a configuration settings class that is needed throughout the app. It is a cross-cutting concern in that it is need in controllers, sometimes deep in the domain logic, as well as place like HtmlHelper extensions. The fact that it's needed is so many different places is what is tripping me up.
The class will wrap settings that are pulled from the web.config, as well as a table in a DB. The DB settings query will be cached so I'm not worried about that getting hit up for every request.
In years past I may have created some static type of class or singleton, but I don't want to lose the testability I have now. What would be the best way to instantiate this class and then to be able to access it through pretty much anywhere in the app?
I would continue to use a singleton. But a singleton which is wrapping an interface, which also makes it testable.
public class Configuration
{
private IConfiguration _config;
public static IConfiguration Instance { get { return _config; }}
public static void Assign(IConfiguration config)
{
_config = config;
}
}
Simply use Assign in global.asax or any of your unit tests.
If you want to do it the correct way, you should provide the configuration settings directly in the constructors of your objects.
Instead of
public class MyService
{
public MyService()
{
var confString = Configuration.Instance.GetConnectionString()
}
}
You would do:
public class MyService
{
public MyService(string confString)
{}
}
Finally, I would not have any configuration dependencies in HTML helpers. By doing so yuo are adding business logic to your views which breaks separation of concerns
I think the codeplex project mvccontrib provided some hooks to use
at least 3 IOC providers as far as I not windsor, structurmap, spring.net...
but I did not used it myself
you can find out more here
http://mvccontrib.codeplex.com/
and maybe you can look into the sourcecode of this project and see where you can go from there...
HTH
I would refactor my app not to use configuration everywhere. I use configuration in controllers only. My views do not have any logic, my domain model does just have business logic, not application logic.

Resources