AutoFac DI in static class - asp.net-mvc

We have a ASP.NET project, and we use AutoFac to DI.
We have a Service layer with all database queries and we need to make some queries in a static class.
This is how we register the dependencies in the Global.asax:
public class Dependencies
{
public static void RegisterDependencies()
{
var builder = new ContainerBuilder();
builder.RegisterControllers(typeof(MvcApplication).Assembly).PropertiesAutowired();
builder.RegisterModule(new ServiceModule());
builder.RegisterModule(new EfModule());
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
}
}
public class ServiceModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterAssemblyTypes(Assembly.Load("MyApp.Service")).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces().InstancePerLifetimeScope();
}
}
public class EfModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType(typeof(myDataContext)).As(typeof(IMyContext)).InstancePerLifetimeScope();
}
}
And this is how we access in the controller:
public class SomeController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
public SomeController(IService1 service1, IService2 service2)
{
_service1 = service1;
_service2 = service2;
}
public ActionResult Index()
{
var service = _service1.GetAll();
...
return View(searchModel);
}
}
Now we need to retrieve data from the database in a static class, so we have to call our service layer, but we don't know how to do it...we have seen this, but I don't know if it is correct, but it works.
public static Test ()
{
...
var service1 = DependencyResolver.Current.GetService<IService1>();
...
}
Also, how it would be in both, non-static and static classes?
Thanks in advance.

The problem is I have to call many of those classes from different places and I don't want to depend on having the service in order to call the class, I'd like the class to take care of everything.
In this case you should register your class with Autofac so that it gets its dependencies injected:
builder.RegisterType<MyClass>();
If the class is used several times during a single request it might be useful to register it using InstancePerLifetimeScope(), but that depends on your overall architecture. See this link to the Autofac documentation for more information.
Of course you have to change your class so that the methods are not static any more and add an constructor to get the dependencies:
public class MyClass
{
private readonly IService1 _service1;
public MyClass(IService1 service1)
{
_service1 = service1;
}
public void Test
{
// use the _service1 instance to do whatever you want
}
}
Now you can inject the MyClass dependency in your controller and use it without having to know anything about its internals or its dependencies:
public class SomeController : Controller
{
private readonly IService1 _service1;
private readonly IService2 _service2;
private readonly MyClass _myClass;
public SomeController(IService1 service1, IService2 service2, MyClass myClass)
{
_service1 = service1;
_service2 = service2;
_myClass = myClass;
}
public ActionResult Index()
{
var service = _service1.GetAll();
...
_myClass.Test();
return View(searchModel);
}
}

Related

Creating an OrmLite repository base class for ASP.NET

I'm trying to create a general base class that I can use in my whole project. I've written some code but still getting a NULL instance on my DbConnectionFactory.
I've create a ASP.Net web api project and added the AppHost file. I'm using Funq together with Simple Injector to Injector my custom services into the Api Controllers.
AppHost.cs
public class AppHost : AppHostBase
{
public AppHost() : base("Erp", typeof(AppHostService).Assembly)
{
}
public override void Configure(Container container)
{
// init
var simpleInjectorContainer = new SimpleInjector.Container();
var erpConnection = ConnectionStrings.ErpLocal;
var isLocal = HelperTools.IsLocalPath();
// check
if (isLocal)
{
erpConnection = ConnectionStrings.ErpOnline;
}
// mvc
ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
// register funq services
container.Register<IErpDbConnectionFactory>(c => new ErpDbConnectionFactory(erpConnectionString));
container.RegisterAutoWiredAs<CategoryService, ICategoryService>();
container.RegisterAutoWiredAs<ManufacturerService, IManufacturerService >();
container.RegisterAutoWiredAs<ProductService, IProductService>();
container.RegisterAutoWiredAs<ProductAttributeService, IProductAttributeService>();
container.RegisterAutoWiredAs<SpecificationAttributeService, ISpecificationAttributeService>();
//...
// simple injector services
SimpleInjectorInitializer.Initialize(simpleInjectorContainer, isLocal);
// register SimpleInjector IoC container, so ServiceStack can use it
container.Adapter = new SimpleInjectorIocAdapter(simpleInjectorContainer);
}
}
Base Class I'm trying to use
public abstract class ApiOrmLiteController : ApiController
{
IDbConnection _erpDb;
public virtual IErpDbConnectionFactory ErpDbConnectionFactory { get; set; }
public virtual IDbConnection ErpDb => _erpDb ?? (_erpDb = ErpDbConnectionFactory.OpenDbConnection());
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
_erpDb?.Dispose();
}
}
Web Api Controller
public class ShippingController : ApiOrmLiteController
{
#region Fields
private readonly IOrderService _orderService;
private readonly IAddressService _addressService;
private readonly ICustomerService _customerService;
private readonly IPdfService _pdfService;
private readonly IMessageService _messageService;
private readonly ITranslationService _translationService;
#endregion Fields
#region Ctor
public ShippingController(IOrderService orderService, IAddressService addressService, ICustomerService customerService, IPdfService pdfService, IMessageService messageService, ITranslationService translationService)
{
_orderService = orderService;
_addressService = addressService;
_customerService = customerService;
_pdfService = pdfService;
_messageService = messageService;
_translationService = translationService;
}
#endregion Ctor
[HttpGet]
[System.Web.Http.Route("Test")]
public void Test()
{
var products = ErpDb.Select<Category>();
}
}
You may need to use constructor injection for Web API or MVC controllers, alternatively you can access dependencies in ServiceStack's IOC via HostContext.TryResolve<T>, e.g:
public virtual IDbConnection ErpDb => _erpDb ??
(_erpDb = HostContext.TryResolve<IErpDbConnectionFactory>().OpenDbConnection());

Play and Guice Dependency Injection with Interface

I'm trying to use Play/Guice dependency injection with an interface:
public interface IService {
Result handleRequest();
}
public Service implements IService {
#Override
public Result handleRequest() {
...
return result;
}
}
public class Controller {
private final IService service;
#Inject
public Controller(IService service) {
this.service = service;
}
}
I get:
play.api.UnexpectedException: Unexpected exception[CreationException: Unable to create injector, see the following errors:
1.) No implementation for IService was bound.
If I change the controller class to not use the interface it works fine:
public class Controller {
private final Service service;
#Inject
public Controller(Service service) {
this.service = service;
}
}
How do I make it work with the interface so it finds the concrete Service class?
You can use guice annotation #ImplementedBy like this:
import com.google.inject.ImplementedBy;
#ImplementedBy(Service.class)
public interface IService {
Result handleRequest();
}
Or u can use modules like this:
import com.google.inject.AbstractModule;
public class ServiceModule extends AbstractModule {
protected void configure() {
bind(IService.class).to(Service.class);
}
}
And then register them in application.conf play.modules.enabled += "modules.ServiceModule"

Quartz .net does not work when I inject dependency

I am using Quartz .net v2.3.3.0 and Castle Windsor v3.3.0.0.
I have a job which is dependent on a Service
public class DemoJob : IJob
{
private readonly IService _Service;
public DemoJob(IService Service)
{
_Service = Service;
}
public void Execute(IJobExecutionContext context)
{
_Service.CallRepoMethod();
}
}
This is the service class which is in different project
public class Service: IService
{
public void CallRepoMethod()
{
Repo();
}
}
Everything works fine till now.
But as soon as I inject dependency in service class the job is not executed.
public class Service: IService
{
private readonly IRepository _repository;
Service(IRepository repository)
{
_repository = repository;
}
public void CallRepoMethod()
{
_repository.Repo();
}
}
IRepository is implemented by a simple Repository class with a single method.
Repository class is in different project and IService,Service and IRepository are in same project.
I don't get any error message but the job does not get executed. If i remove dependency from the Service class then everything works fine and jobs execute.
Here is how I have registered the dependencies
internal class CastleWindsorContainer : IContainer
{
public static WindsorContainer Container { get; private set; }
public CastleWindsorContainer()
{
Container = new WindsorContainer();
}
public void Register()
{
Container.Register(Component.For<IRepository>().ImplementedBy<Repository>().LifestyleTransient());
public Object Resolve(Type controllerType)
{
return Container.Resolve(controllerType);
}
public void Release(IController controller)
{
Container.Release(controller);
}
public void RegisterJobs(IJobFactory jobFactory)
{
Container.Register(Component.For<IJobFactory>().Instance(jobFactory).LifestyleTransient());
Container.Register(Component.For<IQuartzInitializer>().ImplementedBy<JobsConfig>().LifestyleTransient());
Container.Register(Component.For<IService>().ImplementedBy<Service>().LifestyleTransient());
Container.Register(Component.For<DemoJob>().ImplementedBy<DemoJob>().LifestyleTransient()
);
Container.Resolve<IQuartzInitializer>().RegisterJobs();
}
}
code in Global.asax
var container = new CastleWindsorContainer();
IJobFactory jobFactory = new WindsorJobFactory(container);
container.Register();
container.RegisterJobs(jobFactory);
I am not able to figure out what's wrong. I searched for the solution and found many links but it didn't help because all of them show only one level of dependency. What if the dependent class is dependent on another class?
You can find my demo project here:DemoProject
Some links I checked
Quartz .net Windsor Facility
Thank You

Asp.Net MVC and Strategy pattern

I have an MVC application that uses Entity Framework. I am using a repository, unit of work and unity as dependency injection.
The problem I have is that I have different authentication types, and each type I want a different class, so I decided to use the Strategy pattern
public interface IAuthStrategy
{
OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
}
public class AuthStrategy
{
readonly IAuthStrategy _authStrategy;
public AuthStrategy(IAuthStrategy authStrategy)
{
this._authStrategy = authStrategy;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
return _authStrategy.GetAuthenticationMechanism(userName);
}
}
public class UserNamePasswordMechanism : IAuthStrategy
{
private IInstitutionRepository _institutionRepository;
public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
{
this._institutionRepository = institutionRepository;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
throw new NotImplementedException();
}
}
My problem is that I am injecting IAuthStrategy into the controller, and it gives me an error, because instead of implementing IAuthStrategy, I am passing that to AuthStrategy constructor, as you can see that in my code.
How can I fix this error?
Here is my controller
public class EmployeeController : ApiController
{
private IAuthStrategy _auth;
public EmployeeController(IAuthStrategy auth)
{
this._employeeBL = employeeBL;
this._auth = auth;
}}
}
Here is unity config where i am registering my types
public class UnityConfig
{
#region Unity Container
private static Lazy<IUnityContainer> container = new Lazy<IUnityContainer>(() =>
{
var container = new UnityContainer();
RegisterTypes(container);
return container;
});
/// <summary>
/// Gets the configured Unity container.
/// </summary>
public static IUnityContainer GetConfiguredContainer()
{
return container.Value;
}
#endregion
/// <summary>Registers the type mappings with the Unity container.</summary>
/// <param name="container">The unity container to configure.</param>
/// <remarks>There is no need to register concrete types such as controllers or API controllers (unless you want to
/// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.</remarks>
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
container.RegisterType<IInstitutionRepository, InstitutionRepository>();
container.RegisterType<IAuthStrategy, AuthStrategy>();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
Your unit registrations and classes look a little off.
From what I can gather, this is what you really want to do.
Setup a factory that will determine at runtime which IAuthStrategy should be used:
public interface IAuthStrategyFactory
{
IAuthStrategy GetAuthStrategy();
}
public class AuthStrategyFactory : IAuthStrategyFactory
{
readonly IAuthStrategy _authStrategy;
public AuthStrategy(...)
{
//determine the concrete implementation of IAuthStrategy that you need
//This might be injected as well by passing
//in an IAuthStrategy and registering the correct one via unity at startup.
_authStrategy = SomeCallToDetermineWhichOne();
}
public IAuthStrategy GetAuthStrategy()
{
return _authStrategy;
}
}
This is your existing AuthStrategy:
public interface IAuthStrategy
{
OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName);
}
public class UserNamePasswordMechanism : IAuthStrategy
{
private IInstitutionRepository _institutionRepository;
public UserNamePasswordMechanism(IInstitutionRepository institutionRepository)
{
this._institutionRepository = institutionRepository;
}
public OperationResponse<AuthenticationMechanismDTO> GetAuthenticationMechanism(string userName)
{
throw new NotImplementedException();
}
}
Register the factory with unity:
container.RegisterType<IAuthStrategyFactory, AuthStrategyFactory>();
In your controller:
public class EmployeeController : ApiController
{
private IAuthStrategy _auth;
public EmployeeController(IAuthStrategyFactory authFactory)
{
this._employeeBL = employeeBL;
this._auth = authFactory.GetAuthStrategy();
}
}
Actually i missed implemented IAuthStrategyFactory on AuthStrategyFactory, once i implemented and register in unity container that worked.
Thanks

Autofac, multiple interfaces to same implementation per HTTP request in ASP.NET MVC

My DbContext implementation implements two interfaces.
I'm trying to follow best practices and instantiate one DbContext instance per HTTP request.
However, I have a controller action where I need to instantiate two classes, each of which takes different interface in constructor.
I am worried if in that scenario, for that specific action, two DbContext instances would be raised.
I've setup my ContainerBuilder like this:
builder.RegisterType<MyDbContext>()
.As<IWorkflowPersistenceStore>()
.As<IDocumentPersistenceStore>()
.InstancePerHttpRequest();
builder.RegisterType<WorkflowManager>().As<IWorkflowManager>().InstancePerHttpRequest();
builder.RegisterType<DocumentManager>().As<IDocumentManager>().InstancePerHttpRequest();
public class OperationController : Controller
{
private IWorkflowManager _workflowManager;
private IDocumentManager _documentManager;
public OperationController(IWorkflowManager workflowManager, IDocumentManager documentManager)
{
_workflowManager = workflowManager;
_documentManager = documentManager;
}
public ActionResult SaveWorkflowDocument(...)
{
// will my managers point to same DbContext?
_workflowManager.DoSomething(...);
_documentManager.DoSomethingElse(...);
return View();
}
}
public class WorkflowManager : IWorkflowManager
{
private IWorkflowPersistenceStore _store;
public WorkflowManager(IWorkflowPersistenceStore store)
{
_store = store;
}
}
public class DocumentManager : IDocumentManager
{
private IDocumentPersistenceStore _store;
public DocumentManager (IDocumentPersistenceStore store)
{
_store = store;
}
}
Is this good enough?
Do I have to add .SingleInstance()? I'm worried that it might create singleton for whole application.
I think you're ok with what you have. Test passes:
using Autofac;
using NUnit.Framework;
namespace AutofacTest
{
[TestFixture]
public class ScopeTest
{
[Test]
public void Test()
{
var builder = new ContainerBuilder();
builder.RegisterType<Component>()
.As<IServiceA>()
.As<IServiceB>()
.InstancePerLifetimeScope();
using (var container = builder.Build())
using (var scope = container.BeginLifetimeScope())
{
var a = scope.Resolve<IServiceA>();
var b = scope.Resolve<IServiceB>();
Assert.AreEqual(a, b);
}
}
}
public interface IServiceA { }
public interface IServiceB { }
public class Component : IServiceA, IServiceB { }
}

Resources