ASP.NET-MVC-5 dependency Injection - asp.net-mvc-5

I’m a newbie to mvc 5 dependency injection,I know that mvc 5 has a default parameterless constructor.But in dependency injection we create a constructor with a parameter, and IOC containers provide object to the parameter.my question is how does IOC containers like unity make mvc 5 understand the parametered constructor

The basic way that it works is that you ask the IoC container for a type ("resolve") and it will use reflection to look for the constructor (for Unity, the one with the most arguments if they are multiple constructors). It will then repeat the process for each of the argument types themselves, like a tree all the way down the dependency graph. Unity will be able to create instances of concrete types automatically but if the constructor uses an interface or abstract type then it needs to know which implementation to use so in these cases, you need to register the type beforehand:
Register:
e.g. container.RegisterType<IUserHelper, UserHelper>();
Resolve:
e.g. container.Resolve<IUserHelper>();
IOC containers do not work with MVC out of the box but extra libraries exist such as Unity.MVC5 which hook into the MVC pipeline so when MVC tries to create a controller, it uses the IoC container instead of newing up the controller directly (which would fail unless it is parameterless).
Here is an example:
public class MyController(IUserHelper userHelper, IRepository repository) : Controller
Then we could have:
public class MyRepository(IDbContext dbContext) : IRepository
and
public class MyDbContext () : IDbContext
If we use RegisterType to register the IUserHelper, IRepository and IDbContext then when MVC needs to create the controller, it will be able to build the controller complete with all the dependencies.

Related

How to use NESTJS modules in separate classes

Sometimes I need to use some methods which implemented in nestjs code structure in separate from this classes
For example we have such architecture:
entities
-entity.entity.ts
-entity.module.ts
-entity.service.ts
-entity.providers.ts
So how Can I use method or property from entity.service in separate class? Such like this:
import EntityService from './entities.entity.service'
export class SeparateClass{
propertyFromEntityService: string
constructor() {
this.propertyFromEntityService = EntityService.propertyFromEntityService
}
}
And one more important point. I don’t want to implement this separate class in the nestjs structure, I just want to use it as a regular class. Thank you
If you are not wanting to use dependency injection via Nest, but you still want to use a property from a class in the Nest application, you'll need to manually instantiate the class, providing whatever dependencies that class has, and then pulling the property from the service. The other option, if this class will be used outside of the Nest context, but still while the Nest application is running, is you can use the Nest application to get the service via app.get(EntityService), but this does require you to have access to app after the NestFactory has created the application.

Does ServiceStack's default IoC have something similar to ninject's .ToFactory() Method?

Using ninject, I'm able to create an abstract factory using the following syntax from the application's composition root:
kernel.Bind<IBarFactory>().ToFactory();
Does ServiceStack's default IoC container similar functionality? I'd like to implement an abstract factory in one of my service classes in order to create repositories as needed.
One suggestion I've heard was to use:
HostContext.Container.Resolve<[InsertDependancyHere]>()
but I'd like to avoid creating access to the container outside of the composition root (the Apphost.cs file).
As far as i could tell, ServiceStack's Funq IoC implementation does not include this Abstract Factory implementation, like Ninject's Abstract Factory support (or Castle Windsor's Typed Factory Facility, which i used to use).
You can still avoid Service Locator anti-pattern by creating a concrete Factory implementation and injecting that to your classes.
public class BarFactory : IBarFactory
{
// constructor inject dependencies to the factory - no service locator
public BarFactory() { ... }
// create objects from factory
public IBar GetBar() { ... }
}
Your other classes can inject IBarFactory and call it directly.
Func is bare-bones by design, so will not have all the same features. ServiceStack added some features, but mostly having to do with autowiring registration.
If you can't create a concrete implementation for your factories, this other SO answer may show you how to do it yourself.

Servicestack - Grouping like services together

Was wondering if there's a recommended best-practice way of grouping similar services together in what's becoming a larger and larger project. Say that most of my services can be lumped in either dealing with "Pro" data or "Amateur" data (the data goes way beyond a simple flag in a table, the data itself is totally different, from different tables, on the pro or amateur side.
I know I can add routes to my classes...
/pro/service1
/am/service2
It looks like I can put the DTOs in namespaces....
What about the Service.Interface items (Service and Factory classes). Would you put those into namespaces also?
Finally, is there a way for the metadata page to reflect these groupings? I started to go down this road, but all the services listed out in alphabetical order, and you couldn't see the route or namespace differences between service1 and service2.
thank you
If you want, you can split multiple Service implementations across multiple dlls as described on the Modularizing Services wiki.
You can safely group service implementation classes into any nested folder groupings without having any impact to the external services. But changing the namespaces on DTO's can have an effect if your DTO's make use of object, interfaces or abstract classes which emit type info containing full namespaces.
In ServiceStack v4.09+ (now on MyGet) the MetadataFeature includes the ability to customize the ordering of the metadata page, e.g you can reverse the order of the metadata pages with:
var metadata = (MetadataFeature)Plugins.First(x => x is MetadataFeature);
metadata.IndexPageFilter = page => {
page.OperationNames.Sort((x,y) => y.CompareTo(x));
};
Organising your large project:
For a complex service(s) I setup 4 projects in one solution.
AppHost, This takes care of the configuration of the service. (References Model, Service and Types)
Model, This is the database model (Does not reference other projects)
Service, This is the implementation of the service only, not the interfaces or DTOs (References Model and Types)
Types, This includes my Interfaces, DTOs and routes. (Does not reference other projects)
Having a separate Types library allows the distribution to clients, for example for use with the ServiceStack JsonServiceClient.
Yes you can namespace the Interfaces, DTOs and factory classes, any way you want. They will work as long as they are referenced in your service correctly.
If you are trying to separate more than one service, you should consider separating your service code into logical folders within the Service project. i.e.
/Service/Pro
/Service/Amateur
Wrap the outer code of your Service methods in a public partial static class MyServiceStackApplication, with an appropriate name. Then reference this as the assembly in the AppHost constructor. So for example:
Pro Service (Service Project/Pro/UserActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Pro
{
public class UserActionsService : Service
{
public User Get(GetUserRequest request)
{
}
}
// ...
}
}
Pro Service (Service Project/Pro/OtherActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Pro
{
public class OtherActionsService : Service
{
public Other Get(GetOtherRequest request)
{
}
}
// ...
}
}
Amateur Service (Service Project/Am/UserActions.cs)
public partial static class MyServiceStackApplication
{
public partial class Amateur
{
public class UserActionsService : Service
{
public User Get(GetUserRequest request)
{
}
}
// ...
}
}
etc.
You can see from the above code we can have multiple files, all separated out and organised, but one assembly for ServiceStack to reference in the AppHost:
public AppHost() : base("Pro & Amateur Services", typeof(MyServiceStackApplication).Assembly) {}
Using the reference to the MyServiceStackApplication assembly, and using the partial keyword allows you to organise the code into manageable groupings.
Metadata:
Unfortunately separating the metadata by namespace isn't supported. You could try and customize the MetaDataFeature yourself, but it does seem like a useful feature, being able to separate multiple services where they are hosted in the one ServiceStack application. I would suggest you raise a feature request.
Mythz is bringing out features faster than lightning. :) Seems like he has that covered in the next release and you should be able to apply a custom filter to HostContext.Metadata.OperationNamesMap.

Pluggable service assemblies. How to add list of assemblies without hardcoding tem in the AppHost constructor

I have question about how to make service assemblies pluggable (read them from config file) into the ServiceStack.
I want to register my services assemblies from configuration file and not to hard code them in the AppHost constructor like this:
public appHost() : base("My Pluggable Web Services", typeof(ServiceAssembly1).Assembly, typeof(AnotherServiceAssembly).Assembly) { }
I couldn't find other way to register the assemblies outside of this constructor. The constructor also accepts params and does not have overload for example with IEnumerable<Assembly> as parameter.
The idea is to be able to plug service assemblies without touching the service stack REST web site.
I looked at the Plugin interface but I think it is more suitable to be used to extend the service stack not to dynamically plug service assemblies.
Are there any way to implement such pluggable service assemblies feature with the current service stack release? Can you also add constructor overload that will accept the array of assembly?
Thank you in advance
The purpose of your ServiceStack's AppHost is to be a bespoke class customized for your solution that has hard references to all your service dependencies. It's much easier to verify your application is configured correctly, at build time if you declare your dependencies in code as opposed to un-typed configuration.
Having said that you can override the strategy that ServiceStack uses to discover your Service types by overriding AppHostBase.CreateServiceManager():
protected virtual ServiceManager CreateServiceManager(params Assembly[] assembliesWithServices)
{
return new ServiceManager(assembliesWithServices);
//Alternative way to inject Container + Service Resolver strategy
//return new ServiceManager(new Container(),
// new ServiceController(() => assembliesWithServices.ToList().SelectMany(x => x.GetTypes())));
}
Otherwise you can still do what you want by just passing your assemblies into your AppHost, e.g:
var appHost = new AppHost("Service Name", MyConfig.LoadAssembliesFromConfig());
(new AppHost()).Init();

Mapping to an internal type with AutoMapper for Silverlight

How do I configure my application so AutoMapper can map to internal types and/or properties in Silverlight 5? For example, I have the following type:
internal class SomeInfo
{
public String Value { get; set; }
}
I try to call Mapper.DynamicMap with this type as the destination and I receive the following error at runtime:
Attempt by security transparent method
'DynamicClass.SetValue(System.Object, System.Object)' to access
security critical type 'Acme.SomeInfo' failed.
I've tried instantiating the class first, then passing the instance to DynamicMap as well as changing the class scope to public with an internal setter for the property. I've also marked the class with the [SecuritySafeCritical] attribute. All of these tests resulted in the same error message.
The only way I've been able to get past this is to completely expose the class with public scope and public setters. This is, of course, a problem as I am developing a class library that will be used by other developers and using "internal" scope is a deliberate strategy to hide implementations details as well as make sure code is used only as intended (following the no public setters concept from DDD and CQRS).
That said, what can I do to make it so AutoMapper can work with internal types and/or properties?
(Note: The class library is built for SL5 and used in client apps configured to run out-of-browser with elevated trust.)
This is more of a Silverlight limitation - it does not allow reflection on private/protected/internal members from outside assemblies, see:
http://msdn.microsoft.com/en-us/library/stfy7tfc(VS.95).aspx
Simply put - AutoMapper can't access internal members of your assembly.

Resources