ASP.Net 5 offers an options pattern to easily convert any POCO class into a settings class. Using this I can write my settings in json and then turn them into a typed object that I can inject into my controllers. So, for example, my ConfigureServices method in Startup.cs contains the line
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
and then this gets passed into my controllers' constructors using dependency injection
public ItemsController(IOptions<AppSettings> settings) { /* do stuff */ }
One of my controllers fires up a DNN to do some of its work. To reduce the cost of starting the DNN I do that from the static class constructor. Static constructors are parameterless and so I cannot pass in the required settings object, but I could set a static IOptions<AppSettings> property on the ItemsController from my ConfigureServices method. How do I get at that? Where is the dependency injector and how do I persuade it to hand me an IOptions<AppSettings>?
I think you are looking at the problem wrong. The problem is that you have a static class and are using DI, not how to inject your dependencies into a static class (which cannot be done without resorting to a service locator or another hack).
Most DI containers have a singleton lifestyle, which allows you to share the same instance of an object across your application. Using this approach, there is no need for a static class. Eliminate the static class by replacing it with an singleton instance, and you have an avenue where you can inject dependencies into your constructor.
Related
I am going to work with Dependency Injection for a ASP.NET Web API project.
I understand how constructor Dependency Injection works, but i can't resolve how to make the injector choose between two implementations of the same interface. Lets say for an example that we have an interface like this:
public interface ISender
{
void Send();
void AddReceipment(User user);
}
Then lets say i have 2 implementations of this SmsSender and MailSender using the same ISender interface.
Now i have two API controllers lets call them "MailController" and "SmsController".
Now i want the dependency injector to inject ISender into the MailController with the implementation of the class MailSender and in the SmsController i want to inject ISender too, but with the implementation of the class SmsSender.
Is that possible using AutoFac or Unity container?
If it is, then how would i aproach that?
According to the Autofac docs, you have 4 options to achieve this:
Redesign your interfaces
Change the registrations
Use keyed services
Use metadata
I want to know whether I can use object of service layer marked with #Service annotation and call one of its method in non mvc-spring class ?
Say there is a method getUsers() in service layer which calls getUsers() of Dao layer. In order to use it in contoller I have to add the #Autowired-annotation in the service layer instance. But if I want to use the class method getUsers() in non-mvc class, how can I do that?
In order to use a service, that object must be container managed. That is, this object's life cycle must be managed by Spring (creation, destruction, initialisation,...).
So to inject an instance of your service in an object, it must be a Spring bean too (Service, Component, Controller...).
So, it may be an MVC object, but it doesn't have to.
On the other hand, there is another alternative: use the annotation #Configurable.
An object with this annotation can be application managed but Spring, using byte code aspects, can inject it's dependencies. So although you create the object with a new statement, Spring instruments this call and resolve all the annotated dependencies.
Read this for more detail:
http://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch08s08.html
My application is using SQL Server 2012, EF6, MVC and Web API.
It's also using a repository and assorted files such as:
DatabaseFactory.cs
Disposable.cs
IDatabaseFactory.cs
IRepository.cs
IUnitOfWork.cs
RepositoryBase.cs
UnitOfWork.cs
We already use a service layer between our controllers and the repository
for some complicated business logic. We have no plans EVER to change to a different database and it has been pointed
out to me that the recent thinking is that EF6 is a repository so why build
another repository on top of it and why have all of the files I have above.
I am starting to think this is a sensible approach.
Does anyone know of any examples out there that implement EF6 without a
repository, with a service layer. My search on the web has revealed many
complex code examples that seem over complicated for no reason at all.
My problem is also when using a Service Layer then where do I put:
context = new EFDbContext()
In the controller, the service layer or both ? I read that I can do this with dependancy injection. I already use Unity as an IOC but I don't know how I can do this.
Entity Framework IS already a Unit of Work pattern implementation as well as a generic repository implementation (DbContext is the UoW and DbSet is the Generic Repository). And I agree that it's way overkill in most apps to engineer another UoW or Generic Repository on top of them (besides, GenericRepsitory is considered to be an anti-pattern by some).
A Service layer can act as a concrete repository, which has a lot of benefits of encapsulating data logic that is specific to your business needs. If using this, then there is little need to build a repository on top of it (unless you want to be able to change your backend service technology, say from WCF to WebApi or whatever..)
I would put all your data access in your service layer. Don't do data access in your controller. That's leaking your data layer into your UI layer, and that's just poor design. It violates many of the core SOLID concepts.
But you do NOT need an additional UnitOfWork, or other layers beyond that in most cases, unless your apps are very complex and intended to work in multiple environments...
Setting up Unity for ASP.NET MVC and WebAPI is quite easy if you install and add the Unity.Mvc* and Unity.WebAPI* Nuget packages to your project. (The * is a version number, like 3 or 4 or 5. Look for the appropriate versions for your project. Here are for example the links to the Unity.Mvc 5 package and to the Untity.WebAPI 5 package.)
The usage of these packages is explained in this blog post.
The building blocks are roughly like so:
You build a unity container and register all your dependencies there, especially the EF context:
private static IUnityContainer BuildContainer()
{
var container = new UnityContainer();
container.RegisterType<MyContext>(new HierarchicalLifetimeManager());
container.RegisterType<IOrderService, OrderService>();
container.RegisterType<ICustomerService, CustomerService>();
container.RegisterType<IEmailMessenger, EmailMessenger>();
// etc., etc.
return container;
}
MyContext is your derived DbContext class. Registering the context with the HierarchicalLifetimeManager is very important because it will ensure that a new context per web request will be instantiated and disposed by the container at the end of each request.
If you don't have interfaces for your services but just concrete classes you can remove the lines above that register the interfaces. If a service needs to be injected into a controller Unity will just create an instance of your concrete service class.
Once you have built the container you can register it as dependency resolver for MVC and WebAPI in Application_Start in global.asax:
protected void Application_Start()
{
var container = ...BuildContainer();
// MVC
DependencyResolver.SetResolver(
new Unity.MvcX.UnityDependencyResolver(container));
// WebAPI
GlobalConfiguration.Configuration.DependencyResolver =
new Unity.WebApiX.UnityDependencyResolver(container);
}
Once the DependencyResolvers are set the framework is able to instantiate controllers that take parameters in their constructor if the parameters can be resolved with the registered types. For example, you can create a CustomerController now that gets a CustomerService and an EmailMessenger injected:
public class CustomerController : Controller
{
private readonly ICustomerService _customerService;
private readonly IEmailMessenger _emailMessenger;
public CustomerController(
ICustomerService customerService,
IEmailMessenger emailMessenger)
{
_customerService = customerService;
_emailMessenger = emailMessenger;
}
// now you can interact with _customerService and _emailMessenger
// in your controller actions
}
The same applies to derived ApiControllers for WebAPI.
The services can take a dependency on the context instance to interact with Entity Framework, like so:
public class CustomerService // : ICustomerService
{
private readonly MyContext _myContext;
public CustomerService(MyContext myContext)
{
_myContext = myContext;
}
// now you can interact with _myContext in your service methods
}
When the MVC/WebAPI framework instantiates a controller it will inject the registered service instances and resolve their own dependencies as well, i.e. inject the registered context into the service constructor. All services you will inject into the controllers will receive the same context instance during a single request.
With this setup you usually don't need a context = new MyContext() nor a context.Dispose() as the IOC container will manage the context lifetime.
If you aren't using a repository then I assume you would have some place to write your logic/processing that your service operation would use. I would create a new instance of the Context in that logic/process class method and use its methods directly. Finally, dispose it off right after its use probably under a "using".
The processing method would eventually transform the returned/processed data into a data/message contract which the service returns to the controller.
Keep the data logic completely separate from Controller. Also keep the view model separate from data contract.
If you move ahead with this architecture, you are going to be tightly coupling the Entity Framework with either your service or your controller. The repository abstraction gives you a couple things:
1) You are able to easily swap out data access technologies in the future
2) You are able to mock out your data store, allowing you to easily unit test your data access code
You are wondering where to put your EF context. One of the benefits of using the Entity Framework is that all operations on it are enrolled into a transaction. You need to ensure that any data access code uses the same context to enjoy this benefit.
The design pattern that solves that problem is the Unit of Work pattern, which by the looks of things, you are already using. I strongly recommend continuing to use it. Otherwise, you will need to initialize your context in your controller, pass it to your service, which will need to pass it to any other service it interacts with.
Looking at the objects you have listed, it appears to be a considerate attempt to build this app with enterprise architectural best practices. While abstractions do introduce complexity, there is no doubting the benefit they provide.
I'm using the new .NET 4.0 Caching API, ObjectCache. I've asked a few questions on this area the last few days, and i've hinted to this issue - but thought it's worthwhile to break it out into it's own question.
Because the class is abstract and all the methods are virtual, this means we can create our own custom cache providers.
According to MSDN, ObjectCache does not have to be a singleton, and you can create multiple instances of it in your application.
But to me, this sounds like we need to manage the instantiation and lifetime of this object as well?
I have an ASP.NET MVC 3 Web Application, with StructureMap as my dependency injection container.
I want to have a single, shared cache for my entire web application.
So, i create a very simple class which wraps the ObjectCache class, and provides the unboxing in the methods implementation.
The class takes an instance of ObjectCache in the ctor, and sets this to a private static instance of the cache, which the methods (Add, Get, etc) work off.
E.g
public class CacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Now, here's my DI registry:
For<CacheManager>().Singleton().Use<CacheManager>().Ctor<ObjectCache>("cache").Is(MemoryCache.Default);
In english: When something requests a CacheManager instance, use a singleton instance, and set the ObjectCache parameter to be a MemoryCache instance.
So there's what i have, now the questions:
If i have a class to wrap the ObjectCache, does this class need to be a singleton?
MSDN says ObjectCache is thread-safe, but now that i'm using a singleton, do i need any type of locking to keep the thread safety?
Does the private instance of ObjectCache in my wrapper class need to be static? Does the class itself need to be static?
General thoughts on my overall implementation?
I have not been able to find a decent blog/article on .NET ObjectCache in ASP.NET Web Applications, hence my confusion.
I'm use to using HttpContext.Current.Cache (which is static) and not care about lifetime management for the cache.
Since MemoryCache.Default is a singleton, your stateless class doesn't really need to be one. However, that's completely up to you.
You should not need locking around the ObjectCache instance.
No, and No. Making it static doesn't provide any value. Indicating it's a singleton in StructureMap makes GetInstance<>() always return the same object anyways.
The real value of wrapping ObjectCache would to be abstract the cache implementation so you can change it or mock it. Without an interface this becomes less useful.
An example implementation below...
public interface ICacheManager
{
// add, get, remove, etc
}
public class CacheManager : ICacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Then...
For<ICacheManager>()
.Singleton()
.Use<CacheManager>();
For<ObjectCache>()
.Use(MemoryCache.Default);
If you want to change you cache provider that is still an ObjectCache in the future, then it's easy to adjust.
I hope this helps!
I want to call to a method from an EJB in the same instant in which one deploys itself, without using a servlet.
Thanks.
David.
There seems to be no life-cycle methods defined by the EJB spec for this purpose. Individual vendors may provide extensions to allow this. For example Startup Beans in WebSphere would be a place to put the invocation logic you want.
Using techniques such as a static method seem slightly dangerous in that we don't know whether all dependency injection is complete before that static method fires, and hence whether you can safely use the business methods of the EJB.
Persoanlly, if I needed to be portable I would bite the bullet and use a servlet. It costs very little.
Try doing your initialization within a static block. This will run once when the classloader loads the class.
static { System.out.println("static"); }
The PostConstruct hook is right for that.
Find more info on about PostConstruct here:
in the javadoc
lifecycle of EJBs in the JavaEE 5 tutorial
Let's finish with a quick example:
#Stateless
public class TestEJB implements MyEJBInterface{
#PostConstruct
public void doThatAfterInitialization() {
//put your code here to be executed after creation and initialization of your bean
}
}
Static initializer blocks are technically not illegal in EJB but they are used to execute code before any constructor (which might be a problem) when instantiating a class. They are typically used to initialize static fields which may be illegal in EJB if they are not read only. So, what about using ejbCreate(), setSessionContext() or setEntityContext() methods instead (not even sure this would be appropriate without more details on the problem you are trying to solve)?
The EJB container, for a #Singleton bean, shall create the instance of the bean as soon as the application is deploy if it is annotated #Startup.
That will, of course, fire up static initialization blocks, the constructor, dependency injection setters, #PostConstruct methods etc.
Here is the appropriate referente to the Java EE 6 Tutorial.