Mix "traditional" controllers with Castle-Windsor controllers. Is this possible? - asp.net

I'm integrating a series of controllers into an existing project which already contain controllers which use Castle Windsor for DI/IoC. I've modified the Installer to only register Controllers in a certain namespace (specifically the root). This modification appears to be working. When I try to access my controllers, which do not use Castle Windsor and are located in a different namespace (specifically, a custom Area), I get the error message: "No component for supporting the service [Controller Name] was found".
Is it possible to mix "traditional" controllers with controllers which use Castle Windsor in a single project?
Does this make sense?

If you are getting that error, you are trying to resolve the controller (directly or indirectly) through the container.
If you have a separate logic path that needs a controller that isn't register from the container, nothing is stopping you from calling new MyController().
As an aside, thinking in terms of the controller using the container is somewhat backwards. The container manages your instances--your instances have no idea whether they are container-managed or not.

Related

Unity DI - C# Dependency Injection how to use with a repository class constructor ? It's only intended for controllers?

i wanna know if it's possible to inject dependency for a class constructor as it is injected for controllers, i have the following cenario as an example:
An AccountController which depends on an AccountRepository like bellow:
public AccountController(IAccountRepository repository)
The dependency is injected perfectly using Unity DI, which have the following configuration:
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager(), accountInjectionConstructor);
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IdentityDbContext<ApplicationUser>, ApplicationDbContext>(new HierarchicalLifetimeManager());
The problem is that i have a class AuthorizationServiceProvider which also needs the AccountRepository... In this case, how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?
Provider = new SimpleAuthorizationServerProvider>(),
This provider is set inside the Startup class and called before the Unity DI config initializes...
Here the visual studio complains that there's no argument given that corresponds to the class constructor, but if i provide a new AccountRepository i'd have to provide all it's dependencies as well, (ApplicationDbContext context, UserManager userManager) which are already provided for the Unity DI when creating the controllers....
Could somebody help me please?
Thanks in advance...
how would i instantiate or use this AuthorizationServiceProvider class without having to instantiate and provide it all the dependencies?
You can't. This is actually the core of what we're trying to achieve with Dependency Injection. Your application code should let go of the control over its dependencies. This means that your application code should not create an AuthorizationServiceProvider. Rather, it should let a third-party provide this dependency. Typically, this means you require the dependency be supplied using Constructor Injection.
Letting application code create these dependencies itself causes problems, typically referred to as the Control Freak anti-pattern or Dependency Inversion Principle violation. It causes strong coupling, which can hinder maintainability.
When working with Dependency Injection, this third-party is called the Composition Root. The Composition Root is:
a (preferably) unique location in an application where modules are composed together.
With DI, only the Composition Root will create graphs of objects. You are using Unity, which is a DI Container. The DI Container acts as the Composer, which is part of your Composition Root.
Instead of using a DI Container, you can build the object graphs by hand, which means you will have to create a complete tree of dependencies at once. This practice is called Pure DI. Still, the Composition Root is the location where those object graphs are created; with or without a DI Container.
Your view of DI might be troubled by the use of the standard Identity template that Visual Studio provides. From a design and DI perspective, however, this template is horrifying.
Either way, all these stated concepts, patterns and anti-patterns are described quite thoroughly in the book Dependency Injection in .NET by Mark Seemann.

How to create individual dll of asp.net mvc project pages? [duplicate]

I'm just learning asp.net mvc and I'm trying to figure out how to move my controllers into a separate project. Typically when I have designed asp.net web apps before, I created one project for my models, another for my logic, and then there was the web.
Now that I'm learning asp.net mvc I was hoping to follow a similar pattern and put the models and controllers each into their own separate projects, and just leave the views/scripts/css in the web. The models part was easy, but what I don't understand is how to make my controllers in a separate project be "found". Also, I would like to know if this is advisable. Thanks!
First of all, it is certainly a good idea to put your model into a separate project. As you've discovered, this is trivial.
Regarding Controllers and Views, I don't see any obvious advantage to separating them for most basic projects, although you may have a particular need to do so in a particular application.
If you do choose to do this, then you will need to tell the framework how to find your controllers. The basic way to do this is by supplying your own ControllerFactory. You can take a look at the source code for the DefaultControllerFactory to get an idea for how this is done. Subtyping this class and overriding the GetControllerType(string controllerName) method may be enough to accomplish what you're asking.
Once you've created your own custom ControllerFactory, you add the following line to Application_Start in global.asax to tell the framework where to find it:
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
Update: Read this post and the posts it links to for more info. See also Phil Haack's comment on that post about:
ControllerBuilder.Current.DefaultNamespaces.Add(
"ExternalAssembly.Controllers");
...which is not a complete solution, but possibly good enough for simple cases.
While it is reasonable to create your own ControllerFactory, I found it more convenient to define all my Controllers in each project, but derive them from Controllers in my Shared project:
namespace MyProject1.Controllers
{
public class MyController : MySharedProject.Controllers.MyController
{
// nothing much to do here...
}
}
namespace MySharedProject.Controllers
{
public abstract class MyController : System.Web.Mvc.Controller
{
// all (or most) of my controller logic here...
}
}
This has the added benefit that you have a place to put your Controller logic that differs from project to project. Also, it is easier for other developers to quickly find your Controller logic because the Controllers exist in the standard place.
Regarding whether this is advisable, I think it absolutely is. I've created some common Account Management logic that I want to share between projects that otherwise have very different business logic. So I'm sharing my Account and Admin Controllers, but the other Controllers are specific to their respective projects.
Add the Class Library for your mvc project.
In the class add the following code(For u'r Controller Code)
namespace ContactController
{
public class ContactController : Controller
{
public ActionResult Call()
{
ViewBag.Title = "Inside MyFirst Controller.";
return View();
}
}
}
On the mvc project view folder add the folder for Contact and create a Call.cshtml file.
Add the class library project reference into your main MVC project.
Finally to refer contact controller namespace into Route Config.
My problem solved after I updated System.Web.Mvc NuGet reference so MvcWebsite and Class Library use same System.Web.Mvc version
No need to add default namespaces
The simplest form of separation I use is to retain the Views "as is" in the original MVC project but remove the Controllers. Then in a new ClassLibrary project add the Controller classes and ensure they inherit from Controller.
The MVC routing engine will automatically route to the Controllers in the ClassLibrary and the Controllers will automatically construct the Views from the original MVC project, provided you have your references and usings correctly in place.
I am using this architecture to implement an Html Reports module that can be compiled and deployed separately from the main solution. At last I am free from SSRS!

ASP.NET 5 dependency injection outside of Controllers and Views

Each tutorial or example that I've found for using DI in ASP.NET 5 only shows how it works with Controllers and Razor Views. I need to use DI for other classes but don't know the proper way to resolve types and provide an instance. Right now I have an instance of a HackyDependencyResolver that everything must reference in order to get the proper instances. I want to either access ASP.NET's service resolver or follow some other best-practice for resolving dependencies.
For example if I have
public class SomeClass
{
public SomeClass(IUseMe useMe)
{
}
}
which is not an ASP.NET MVC Controller. I need a pattern for resolving a correct instance for IUseMe when SomeClass is created. Certainly I can make my own global factory, but is that the best way?
DI has nothing to do with asp.net, controllers or views. In the end all are classes. Considering that an action is an entrypoint in your app, any service you need there should be injected, The service itself has some dependencies and those will be injected automatically by the DI Container when it instantiates the controller.
All you have to do is to define your services (not every object needs injected deps) then register those services into the Di Container.
How do I resolve IUseMe so that I'm not dependent on a particular implementation?
You don't. The Di Container does that based on configuration, when the controller is instantiated. Everything has a flow, you don't just pick classes out of thin air and say "I want this created by the Di container". OK you could, but it would be the wrong approach.
The whole point of using a DI Container is not to care about instantiating services. The framework takes care of integrating with the container, your only job is to define the classes properly and to configure the container .

spring based bundle in apache felix osgi

I am working one POC where I want to create plugin based web application. Main application will have all the spring mvc context. Plugins can write spring controllers but they cannot have their own spring context file. What I want is when plugin is installed all its controller is scanned (plugins controller need to be in specific package so for that package component scan will be defined in parent context) and ready to use. I am able achieve the installation part however when I am trying to access bundle/plugin controller end point through rest call I get no mapping found error.
Has anyone tried something like this? It will be great if I can get reference to some example.
Thanks!!!
If you remove the spring part, I've already done this with
a) Apache Wicket and Pax Wicket
b) Vaadin
For a) you might want to look at the Apache Karaf WebConsole.
For b) take a look at this rather "old" showcase of mine.
Both of those showcases use either standard OSGi services or Blueprint for the services (http-services) and the discovery of new "web-components" or views.

Silex - real DI vs injecting $app which looks like ServiceLocator?

I read the article yesterday: https://igor.io/2012/11/09/scaling-silex.html
And another one http://davedevelopment.co.uk/2012/10/03/Silex-Controllers-As-Services.html
So a conceptual question rised in my head:
Currently I do have a lot of controllers in separate classes. I overwrite controller_resolver to create a controller class instance and inject $app into contoller's constructor.
I define routes like this $app->get('/hello', 'HelloController::indexAction') <- my controller resolver will create new HelloController($app); - so far so good.
But to be honest it became a ServiceLocator pattern, not a DependencyInjection, because I do inject whe whole $app which looks like ServiceLocator usage.
Now I am in doubt: should I leave it as is (because it works well) or try "controllers as services" to inject only those sevices on which my controller really depends on? May be my SeviceLocator approach will hit me some day? (people say that DI is better for tests).
I have also looked into Symfony Framework Bundle: class Controller extends abstract class ContainerAware which also have the whole $container injected! ServiceLocator approach in full stack framework?
Any recomendation? Pros/cons?
The symfony2 full-stack framework
The framework uses the Dependency Injection pattern and not the Service Locator pattern.
All controllers aren't services by default. The ContainerAware class includes methods to get access to the service container, so you can call Services inside the Controller.
If you are going to use a Controller as a Service you need to remove the Controller extend. All dependencies you want to use inside the controller needs to be injected by the Service Container.
Read more about this in a blogpost by richard miller, one of the core contributors of Symfony2.
The Silex micro-framework
The Silex micro-framework provides the bare bones of a framework, it's up to you how the architecture looks and which patterns you use.
The Silex documentation uses Controllers that aren't Services. It injects the complete Service Container inside very Controller:
$app->post('/post/{id}-{slug}', function($id, $slug) use ($app) {
// ...
});
If you want to use controllers as service, you should only inject the services you want to use inside the controller.
EDIT: The Controller::action syntax refers also to a Controller that isn't a Service. The Controller:action notation is used to refer to Controllers as Services.
There's lot's of personal preference involved here. What you've done already is a good (enough) step to organising your code base. Some people like myself take things a step further and move our controllers to the container, rather than injecting it in to some kind of BaseController. This happens in both Silex and the full stack Symfony framework.
My advice would be to leave everything you have as is, then try defining your next controller as a service, by practising BDD.
For example, the behaviour of a UserController view action:
It should retrieve the user from a database
It should render the user with a template
Not once does it mention retrieving the database or the template renderer from a container. I'm comfortable not injecting the container, so I'll only inject what I'm led to believe I need by BDD.

Resources