I am Use this code For select 4 Last Record Of Database in various page
public static List<Tour> GetLastTour()
{
using (var Context = new MvcHghDbContext())
{
return (Context.Tours.Take(4).OrderByDescending(x=>x.Titl e).ToList());
}
}
How To Use unit of work pattern in static Method in Static Class ?
But Static Constructor Erorr!
such this code
plz help me:
public static class DropDownList{
private readonly ICatHotellService _catHotellService;
private readonly ICatTourismService _catTourismService;
private readonly ICatTourService _catTourService;
private readonly IUnitOfWork _uow;
public DropDownList(ICatHotellService CatHotellService, IUnitOfWork ouw, ICatTourService CatTourService, ICatTourismService CatTourismService)
{
_uow=ouw;
_catHotellService = CatHotellService;
_catTourismService = CatTourismService;
_catTourService = CatTourService;`
}
}
The short answer is that this can't work. Static classes may only have static constructors, and these get called by the runtime when the app is created. Thus, this happens long before your dependency injection has been configured. On top of that, you should never ever ever have static data contexts in a web application, because these are shared by all users of your app, thus two users using the same data context will write over each others data model.
You are not using UoW at all. UoW means injecting one instance of the MvcHghDbContext to different classes of your service layer during a request call and not instantiating it directly each time such as your GetLastTour method.
Don't use static classes in your service layer. extract an interface from them and let the IoC container manage its life time.
Also you can use service locator pattern (such as calling ObjectFactory.GetInstance<>) every where even in static classes. It's an anti pattern and should be avoided as much as possible, because now the IoC Container is a dependency in your class.
Related
I understand the basics of DI in .NET Core, but I'm having trouble figuring out how to use it with multiple projects. Imagine I'm setting up a database context in the Startup class of ASP.NET Core:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GalleryDb>();
}
I know how to access that context in an API controller:
public class AlbumController : Microsoft.AspNetCore.Mvc.Controller
{
private GalleryDb _ctx;
public AlbumController(GalleryDb ctx)
{
_ctx = ctx;
}
}
But what does one do when there are many layers and functions between the API controller and the data access class? Eventually the code reaches my repository class, which is the one that actually requires the context. It looks like this:
public class AlbumRepository
{
private GalleryDb _ctx;
public AlbumRepository(GalleryDb ctx)
{
_ctx = ctx;
}
public void Save(AlbumEntity entity)
{
// Use _ctx to persist to DB.
}
}
I understand that I could pass the context from the API entry point all the way down, but that seems like an anti-pattern because it means passing it as a parameter through multiple classes and functions that have no interest in it.
Instead, I'd like to do something like this at the point where I invoke the repository class:
public void Save(AlbumEntity album)
{
var ctx = DependencyResolver.GetInstance<GalleryDb>();
var repo = new AlbumRepository(ctx);
repo.Save(album);
}
I believe some DI frameworks have something like this, but I'm trying to figure out how to do it with native .NET Core 2.0. Is this possible? What is the best practice? I found one thread (ASP.NET Core DependencyResolver) talk about using IServiceProvider but the implication was that this was not a desirable solution.
I'm hoping whatever the solution is, I can extend it to apply to other DI classes like ASP.NET Identity's RoleManager and SignInManager.
The key breakthrough chris-pratt helped me understand is that the only way this works is to use DI through all the layers. For example, down in the data layer I get a DB context through DI:
public class AlbumRepository
{
private GalleryDb _ctx;
public AlbumRepository(GalleryDb ctx)
{
_ctx = ctx;
}
}
In the business layer I use DI to get a reference to the data layer:
public class Album
{
private AlbumRepository _repo;
public Album(AlbumRepository repo)
{
_repo = repo;
}
}
Then, in the web layer, I use DI to get a reference to the business layer class:
[Route("api/[controller]")]
public class AlbumController : Microsoft.AspNetCore.Mvc.Controller
{
private Album _album;
public AlbumController (Album album)
{
_album = album;
}
}
By using DI through every layer, the DI system is able to construct all the necessary classes at the point where they are needed.
This requirement has a profound impact on the architecture of an application, and I now realize that my initial hope to tweak an existing, non-DI app to start using DI for the DB context is a major undertaking.
I understand that I could pass the context from the API entry point all the way down, but that seems like an anti-pattern because it means passing it as a parameter through multiple classes and functions that have no interest in it.
No, that's not an anti-pattern. That's how you should do it. However, the bit about "classes and functions that have no interest in it" makes no sense.
Simply, if you're working with something like a repository that wraps a DbContext (a horrible idea, by the way, but we'll put a pin in that), then you shouldn't ever be dealing directly with that DbContext. Instead, you should be injecting your repository into your controllers and then simply let the context be injected into that:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<GalleryDb>();
services.AddScoped<AlbumRepository>();
}
Since ASP.NET Core knows how to inject GalleryDb, and AlbumRepository takes GalleryDb as a constructor param, you simply register AlbumRepository for injection as well (using a "scoped" or request lifetime).
Now, you can inject AlbumRepository the same way you're currently injecting the context:
public class AlbumController : Microsoft.AspNetCore.Mvc.Controller
{
private AlbumRepository _repo;
public AlbumController(AlbumRepository repo)
{
_repo = repo;
}
}
Where this starts to get tricky is when you have many repositories, especially if you have controllers that need to interact with several repositories. Eventually, your code will become a rat's nest of service config and injection boilerplate. However, at that point, you should really be employing the unit of work pattern as well, encapsulating all your repositories in one class that you can inject instead. But wait, oh yeah, that's what DbContext is already. It's a unit of work encapsulating multiple repositories, or DbSets. This is why you shouldn't being using the repository pattern in conjunction with Entity Framework. It's a pointless abstraction that does nothing but add additional and unnecessary entropy to your code.
If you want to abstract DbContext, then you should use something like the service layer pattern (not to be confused with the RPC bull excrement Microsoft refers to as the "service pattern") or the CQRS (Command Query Responsibility Segregation) pattern. The repository pattern is for one thing: abstracting away raw SQL. If you don't have raw SQL, you should not be implementing that pattern.
In our previous app we used StructureMap and we could write very little code.
before every service we added the dependencies like:
[SetterProperty]
public IXService XService { get; set; }
and in the constructor
ObjectFactory.BuildUp(this);
then in test we could instantiate it simply by
var service = new XService();
Now, we start another app and using asp.net core build-in DI container.
it look like we should write a lot of code, and very long constructor for each test:
private readonly ILogger<AccountsController> _logger;
private readonly IMapper _mapper;
private readonly IAccountBlService _accountBlService;
private readonly IValidationHelper _validationHelper;
private readonly IValidator<AccountDTO> _accountDTOValidator;
private readonly Example _example;
private readonly IConfiguration _configuration;
public AccountsController(BillingContext context, ILogger<AccountsController> logger, IMapper mapper, IAccountBlService accountBlService,
IValidationHelper validationHelper, IValidator<AccountDTO> accountDTOValidator, IOptions<Example> example, IConfiguration configuration)
{
_logger = logger;
_mapper = mapper;
_accountBlService = accountBlService;
_validationHelper = validationHelper;
_accountDTOValidator = accountDTOValidator;
_configuration = configuration;
_example = example.Value;
}
Is there a shorter way we didnt found? is one planned for the near future? should we use StructureMap instead the built-in container? or there are disadvantages for this? thanks!
Is there a shorter way we didnt found?
In short: No, not with the default container. But I recommend you read Dependency Injection in .NET by Mark Seemann (if you have then please ignore me saying this), because have you heard of "Composition Root"? IMHO the way you declared dependencies has the same amount of code, just scattered all over your code base. While you should really keep it in one place for maintainability.
Is one planned for the near future? Not that I know of, but really if you look at it, it's the same amount of code, just centralized. We however use NServiceBus's ability to call "RegisterComponents" on the BusConfiguration which uses reflection to register all dependencies in one call. You could look for containers that can do the same. Now if you're thinking about your tests, if you use XUnit you can set up your SUT via de test class's constructor. Refactor it in factory classes so you only have to write it once. This way you can also throw mocks in to keep your tests clean.
Should we use StructureMap instead the built-in container?
If you wish. We use Autofac.
Or are there disadvantages for this?
Not that we've encountered thus far. Sometimes you need the IServiceProvider for special 'tricks' but there's always a way.
Note: if you are concerned about having 7 dependencies in your controller (which is a lot indeed) there are a few options:
Look at the scope of the dependency. If it's only used in 1 or 2 action methods you can also declare it [FromService] in the action method's signature
Is your controller doing too much? Watch out for god classes. Maybe it needs refactoring. After all, controllers are nothing more than logical collections of action methods.
Can dependencies be combined? Sometimes it seems they need to be seperated, but in most contexts they are always in pairs. It appears there's a high cohesion and you could combine them in a helper class to maintain cohesion.
I've been building an application with Fluent nHibernate/ASP.NET MVC - and I've dug around and figured out that it's considered most appropriate practice to keep a 'permanent' SessionFactory open, and then use sessions for each request to the database. Okay, this sounds good...
I'm quite confused on how to accomplish this, though. Everything I find assumes an entire structured framework that uses some kind of IoC container system ...and that's just too advanced for what I have so far. Are there any more simple examples of how to implement this kind of design?
I've taken a look at Where can I find a good NHibernate and ASP.NET MVC Reference Application
And even read the book "ASP.NET MVC in Action", but it's example is just far more complicated than what I am trying to achieve. I thought a singleton model would work in the Application_Start of the 'global.asax' but that didn't yield the results I had hoped for. It would keep disposing of my factory and never recreating it.
You could expose the ISessionFactory as singleton:
public sealed class FactoryManager
{
private static readonly ISessionFactory _instance = CreateSessionFactory();
static FactoryManager()
{ }
public static ISessionFactory Instance
{
get { return _instance; }
}
private static ISessionFactory CreateSessionFactory()
{
// TODO: configure fluentnhibernate and create a session factory
}
}
Now you could use FactoryManager.Instance in your code:
using (var session = FactoryManager.Instance.OpenSession())
using (var tx = session.BeginTransaction())
{
// TODO: use the session here
tx.Commit();
}
Make a static GetSessionFactory method on your global MvcApplication class. This method initializes a session factory the first time it is called and stores it as a private static variable. Upon subsequent calls, it simply returns the static variable.
This method can also check to see if the object is null or disposed and recreate as necessary, though it shouldn't happen since the variable would be static and thus, stay alive for the duration of the application's lifetime.
I've implemented a repository pattern with persistence ignorance. The repository implementation only interacts with my entity objects, IUnitOfWork and ITable<T> interfaces. The intention is that the IUnitOfWork isn't reused but represents a single transaction. So far, I've implemented in-memory as well as Linq-to-Sql versions of the IUnitOfWork and ITable<T>.
My problem is that due to the IUnitOfWork injection into the repository, I end up with needing to know how to instantiate a new IUnitOfWork where ever the repository is used. Since this is the primary piece that is supposed to be pluggable it feels like I've done something wrong. The general usage pattern is something like this:
FooUnitOfWork unitOfWork = new FooUnitOfWork();
Repository repos = new Repository(unitOfWork);
// ...act upon repos
unitOfWork.Save();
Now it appears that I need some other pattern to allow every repository usage in the app to obtain the correct unit of work (e.g. in-memory, L2S, etc.).
What is the most fitting pattern for this? I've looked at Fowler's discussion on the topic but none of his examples seem to be a clean fit. I already feel like the amount of abstraction that I have is more than I'd like so building yet another indirection seems excessive.
At the moment, I'm leaning toward some sort of app-wide provider which can be configured to produce the correct IUnitOfWork. Am I off-base or is this what is needed to truly be implementation agnostic?
Update: while this didn't really break down it ended up just producing a poor-man's IoC Container. I ended up just replacing all of these:
UnitOfWorkFactory.Create();
with the generalized Common Service Locator implementation:
Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IUnitOfWork>();
This allowed me to create a library which uses Dependency Injection without forcing all users to use the same IoC framework.
Perhaps I should use a very simple factory where I can set a callback? It could have a set of static methods on it like this:
public static class UnitOfWorkFactory
{
private static Func<IUnitOfWork> FactoryMethod;
public static IUnitOfWork Create()
{
if (UnitOfWorkFactory.FactoryMethod == null)
{
throw new InvalidOperationException("...");
}
return UnitOfWorkFactory.FactoryMethod();
}
public static void SetFactoryMethod(Func<IUnitOfWork> factory)
{
UnitOfWorkFactory.FactoryMethod = factory;
}
}
Where does this break down?
I would suggest using a Vistor pattern to discover the implementations of the IUnitOfWork interface.
[UnitOfWork(Name="foo")]
public class FooUnitOfWork : IUnitOfWork {}
Repository repo = new Repository("foo");
//stuff happens
repo.Save(); //or repo.Worker.Save();
Inside the repo instance a discovery factory finds the worker and creates it.
I'm starting to get into Unit Testing, Dependancy Injection and all that jazz while constructing my latest ASP.NET MVC project.
I'm to the point now where I would like to Unit Test my Controllers and I'm having difficulty figuring out how to appropriately do this without an IoC container.
Take for example a simple controller:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository = new SqlQuestionsRepository();
// ... Continue with various controller actions
}
This class is not very unit testable because of its direct instantiation of SqlQuestionsRepository. So, lets go down the Dependancy Injection route and do:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository;
public QuestionsController(IQuestionsRepository repository)
{
_repository = repository;
}
}
This seems better. I can now easily write unit tests with a mock IQuestionsRepository. However, what is going to instantiate the controller now? Somewhere further up the call chain SqlQuestionRepository is going to have to be instantiated. It seems as through I've simply shifted the problem elsewhere, not gotten rid of it.
Now, I know this is a good example of where an IoC container can help you by wiring up the Controllers dependancies for me while at the same time keeping my controller easily unit testable.
My question is, how is one suppose to do unit testing on things of this nature without an IoC container?
Note: I'm not opposed to IoC containers, and I'll likely go down that road soon. However, I'm curious what the alternative is for people who don't use them.
Isn't it possible to keep the direct instantiation of the field and also provide the setter? In this case you'd only be calling the setter during unit testing. Something like this:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository _repository = new SqlQuestionsRepository();
// Really only called during unit testing...
public QuestionsController(IQuestionsRepository repository)
{
_repository = repository;
}
}
I'm not too familiar with .NET but as a side note in Java this is a common way to refactor existing code to improve the testability. I.E., if you have classes that are already in use and need to modify them so as to improve code coverage without breaking existing functionality.
Our team has done this before, and usually we set the visibility of the setter to package-private and keep the package of the test class the same so that it can call the setter.
You could have a default constructor with your controller that will have some sort of default behavior.
Something like...
public QuestionsController()
: this(new QuestionsRepository())
{
}
That way by default when the controller factory is creating a new instance of the controller it will use the default constructor's behavior. Then in your unit tests you could use a mocking framework to pass in a mock into the other constructor.
One options is to use fakes.
public class FakeQuestionsRepository : IQuestionsRepository {
public FakeQuestionsRepository() { } //simple constructor
//implement the interface, without going to the database
}
[TestFixture] public class QuestionsControllerTest {
[Test] public void should_be_able_to_instantiate_the_controller() {
//setup the scenario
var repository = new FakeQuestionsRepository();
var controller = new QuestionsController(repository);
//assert some things on the controller
}
}
Another options is to use mocks and a mocking framework, which can auto-generate these mocks on the fly.
[TestFixture] public class QuestionsControllerTest {
[Test] public void should_be_able_to_instantiate_the_controller() {
//setup the scenario
var repositoryMock = new Moq.Mock<IQuestionsRepository>();
repositoryMock
.SetupGet(o => o.FirstQuestion)
.Returns(new Question { X = 10 });
//repositoryMock.Object is of type IQuestionsRepository:
var controller = new QuestionsController(repositoryMock.Object);
//assert some things on the controller
}
}
Regarding where all the objects get constructed. In a unit test, you only set up a minimal set of objects: a real object which is under test, and some faked or mocked dependencies which the real object under test requires. For example, the real object under test is an instance of QuestionsController - it has a dependency on IQuestionsRepository, so we give it either a fake IQuestionsRepository like in the first example or a mock IQuestionsRepository like in the second example.
In the real system, however, you set up the whole of the container at the very top level of the software. In a Web application, for example, you set up the container, wiring up all of the interfaces and the implementing classes, in GlobalApplication.Application_Start.
I'm expanding on Peter's answer a bit.
In applications with a lot of entity types, it is not uncommon for a controller to require references to multiple repositories, services, whatever. I find it tedious to manually pass all those dependencies in my test code (especially since a given test may only involve one or two of them). In those scenarios, I prefer setter-injection style IOC over constructor injection. The pattern I use it this:
public class QuestionsController : ControllerBase
{
private IQuestionsRepository Repository
{
get { return _repo ?? (_repo = IoC.GetInstance<IQuestionsRepository>()); }
set { _repo = value; }
}
private IQuestionsRepository _repo;
// Don't need anything fancy in the ctor
public QuestionsController()
{
}
}
Replace IoC.GetInstance<> with whatever syntax your particular IOC framework uses.
In production use nothing will invoke the property setter, so the first time the getter is called the controller will call out to your IOC framework, get an instance, and store it.
In test, you just need to call the setter prior to invoking any controller methods:
var controller = new QuestionsController {
Repository = MakeANewMockHoweverYouNormallyDo(...);
}
The benefits of this approach, IMHO:
Still takes advantage of IOC in production.
Easier to manually construct your controllers during testing. You only need to initialize the dependencies your test will actually use.
Possible to create test-specific IOC configurations, if you don't want to manually configure common dependencies.