Best approach between Using and public object? - c#

I would like to know what is the best approach between using statement and creating a public variable.
My example is the following:
I have a manager class which inherits from disposable, and this class has access to my dbcontext and methods to it.
What I am doing now is on my cs class doing a ussing to that class and create and destroy my object to my needs.
For example:
public class StudentManager: IDisposable
{
private ISchoolUnitOfWork _unitOfWork;
public StudentManager()
{
_unitOfWork = new SchoolUnitOfWork();
}
public IEnumerable<Student> GetStudents()
}
On my cs class I do:
private IEnumerable<Stundets> GetStudents()
{
using (StudentManager manager = new StudentManager())
{
return = manager.GetStudents();
}
}
OR
private StudentManager = new Studentmanager();
What is the best way to do it: having the instance of my StudentManager (just create a connection and destroy when leave page) or working with the using?
I am a bit confused about that. Thanks in advance!
I do update my context on the same manager calling the save at my context which is an interface of my unit of work, I do not access directly to the context, but when I construct it I construct one type my unit of work.
I do save on my crud operations on the manager. So on my manager on update, insert, modify I call the save method, for example:
public class StudentManager....
public Student UpdateStudent(Student student)
{
IStudentService service = new StudentService(_unitOfWork.StudentRepository);
Student student= service.Update(student);
_unitOfWork.Save();
return student;
}
In general, I have an Interface IUnitOfWork and a UnitOfWork, also have a IRepository and a repository. And I just use a manager to not instantiate my UnitOfWork directly, but with a manager to it... I think that's legal and useful!

The best way is the using statement because it calls Dispose automatically. You can guarantee that your disposal logic will occur. This is, in fact, how you should use objects like SqlConnection and SqlCommand as well. So you're doing it right with the using.
In fact, you stated that you're using a DbContext to access the data. Those should be instantiated on demand and wrapped in a using as well. There is no need to share an instance of these types of classes because connection pooling is done at the SQL Server via the connection string.

If you use using then might be in a single you need to write similar stuffs more than once. For example
//To get all students
private IEnumerable<Stundets> GetStudents()
{
using (StudentManager manager = new StudentManager())
{
return = manager.GetStudents();
}
}
//To save Students
//To get all students
private IEnumerable<Stundets> SaveStudents()
{
using (StudentManager manager = new StudentManager())
{
return = manager.Save();
}
}
and so on. But here you dont have to worry about the disposing of the object. It will be taken care automatically. If you go for global declaration , you need to do it manually. So what i need to say, If you have to use the StudentManager all over the page why dont you make it global and use it all over the required places, using both.Something like this
private StudentManager manager;
//To get all students
private IEnumerable<Stundets> GetStudents()
{
using (manager = new StudentManager())
{
return = manager.GetStudents();
}
}
//To save Students
//To get all students
private IEnumerable<Stundets> SaveStudents()
{
using (manager = new StudentManager())
{
return = manager.Save();
}
}

Related

Unit of work repository pattern for static class

Task assigned to me is to refactor a code but should't modify static access modifier of class. I am trying to implement service layer , unit of work , repository pattern . static repository code is below , how can i implement unit of work and repository pattern for a static class? i like to implement a solution applying solid principles and unit testable application.
static class
using System;
using System.Data.SqlClient;
namespace Contoso
{
public static class UsersRepository
{
private static string ConnectionString = #"Data Source=(local); Database=Users;User Id=sa;Password=password;";
public static User Load(int userId)
{
User user = new User();
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM Users WHERE UserId = " + userId,
connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
user.Name = reader["Name"].ToString();
user.DateOfBirth = DateTime.Parse(reader["DateOfBirth"].ToString());
user.Country = reader["Country"].ToString();
}
connection.Close();
return user;
}
}
}
How can i implement unit of work and repository pattern for a static class?
You can leverage the fact that whenever someone calls the code here, they do so via a public entry point. This means that when the caller first enters the class (via said public method), you create a unit of work and dispose of it only when that same method returns a value to the caller (or simply ends).
Something along the lines of:
public static class MyClass
{
public static User LoadUser(int userId)
{
using (var uow = new UnitOfWork())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
Essentially, every public method should create, use and dispose of a single unit of work instance. This ensures two things:
Concurrent calls use their own separate unit of work.
No unit of work will ever linger in-memory after the entry method has finished.
This does get trickier when you start using async programming, but I'm omitting that consideration since you never mentioned it either.
i like to implement a solution applying solid principles and unit testable application
It gets slightly trickier when you deal with dependency injection. Static classes do not have an injectable constructor (note: they do have a constructor, but they don't allow for constructor arguments).
So injecting your dependency is going to be... atypical. One solution I can think of is to explicitly set the kernel (I am using NInject here as a matter of example):
public static class MyClass
{
public static IKernel Kernel { get; set; }
public static User LoadUser(int userId)
{
using (var uow = Kernel.Get<IUnitOfWork>())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
How you set the kernel (either by setting it explicitly or assigning it a default value directly) is up to you.
Without NInject or any similar library, you could achieve dependency injection using a Func<IUnitOfWork> as your factory method to create a unit of work on demand:
public static class MyClass
{
public static Func<IUnitOfWork> CreateUnitOfWork { get; set; }
public static User LoadUser(int userId)
{
using (var uow = CreateUnitOfWork())
{
DoSomething(uow);
var user = uow.UserRepository.GetById(userId);
return user;
}
}
}
Again, how you set the factory method's content is up to you, e.g.:
MyClass.CreateUnitOfWork = () => new UnitOfWork();

Implement data access layer best practices in .net Project MVC

I would like to improve my .NET project by adding another layer when accessing the database. This is my code:
namespace Company.Models
{
public static class AgencyBean
{
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static String createGUID(string name)
{
DataAccess dataAccess = new DataAccess();
bool exists = dataAccess.checkIfExists(Id);
if(exist)
{
dataAccess.delete(Id);
}
retur "ok";
}
}
}
I placed DataAccess class in a separate folder called "Helpers" and it contains most of my queries:
public class DataAccess
{
public bool checkIfExists(String Id)
{
try
{
SqlConnection cnn = new SqlConnection(dataConnection);
cnn.Open();
SqlCommand check_Id = new SqlCommand("SELECT COUNT(*) FROM TABLE_GUID WHERE ([USER_ID] = #Id)", cnn);
check_Id.Parameters.AddWithValue("#Id", Id);
int UserExist = (int)check_Id.ExecuteScalar();
if (UserExist > 0)
{
return true;
}
else
{
return false;
}
}
catch (SqlException ex)
{
Debug.WriteLine("SQL Exception " + ex);
DisplaySqlErrors(ex);
throw ex;
}
}
}
public class AgentBeanController : Controller
{
// GET: AgentBean
public ActionResult Index(string name)
{
return View();
}
[AllowAnonymous]
[WebMethod]
public string AgentURL() //here we create Agent URL and return it to the view
{
string var = Models.AgentBean.createGUID("TODO");
return var;
}
}
I'm accessing the database pretty much in very direct way. How would it be with a better technique, so this access can be more secure, like accessing thru a service layer?
I'm connecting to a existing sql database in some server and working with MVC architecture in my project.
So here is what I have done in the past.
First, that is your "models" namespace... models should never have database connectivity. Instead you have a seperate class, such as a controller, that hydrates some model.
Second, I've had a "service" class, which hooks up to a "repository" class. The repository class implements an interface to identify the exact "type" of database you're using.. but if that's not a part of your requirements you probably don't need to go that far.
Third, look up dependency injection (aka, DI). There are several frameworks out there. Personally I've used Autofac, but others exist as well to get the job done easier.
Fourth, on your your "controllers", "services" and "respository" classes, implement dependency injection, as well as any interfaces as needed to form a contract.
Fifth, I would use an actual controller namespace and not be working out of your models namespace to be pushing http calls band and forth.... Instead, create an action in your controller class, and instantiate an instance of your "agencyBean", hydrate it with data, and return that model out to your view.
Basically, in a scenario like this you're trying to keep each component doing what it is designated to do... breaking down responsibilities into smaller pieces and focusing on that. Your controller should just "fetch" your model and maybe do some transformations on it as needed or any other business-type logic.
Your service should handle the communication between your controller and your database layer.
Your data access layer (ie, in this case, some "repository" class...) would do all of those new data connections and/or setting up calls to stored procedures or queries.
Doing things this way has a lot of benefit. Some of the big ones are maintainability, readability, code re-use. Sure it makes your project a bit more complicated in terms of files sitting wherever... but that can be a good thing. It's so much better than slamming everything into one single class and have it do everything :)
But, just FYI, this is from an implementation I've done in the past... I'm sure there are better ways but this setup worked quite well for my team and I.
Here is a small example using some of your code you posted. I DID NOT check this for typos and it wouldn't compile, but should help give a general idea of what I'm talking about....
namespace Company.Models
{
public class AgencyBean
{
public AgencyName{get;set;}
public AgencyId{get;set;}
// other properties...
}
}
namespace Company.Controllers
{
public class MyController : Controller
{
private readonly IMyService myService;
public MyController(IMyService myService) // <-- this is your dependency injection here...
{
this.myService = myService;
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static String createGUID(string name)
{
var model = new AgencyBean();
model.AgencyId = 1;
model = myService.getAgency(agencyBean);
return model;
}
}
}
namespace Company.Services
{
public class MyService
{
private readonly IMyRepository myRepository;
public MyService(IMyRepository myRepository) // <-- this is your dependency injection here...
{
this.myRepository = myRepository;
}
public AgencyBean getAgency(AgencyBean model){
var dataTable = myRepository.getAgencyData(model.AgencyId);
// fill other properties of your model you have...
// ...
// ...
return model;
}
}
}
namespace Company.Repositories
{
public class MyRepository : IDatabaseCommon // <-- some interface you would use to ensure that all repo type objects get connection strings or run other necessary database-like setup methods...
{
private readonly String connectionString{get;set;}
public MyRepository()
{
this.connectionString = //get your connection string from web.config or somewhere else...;
}
public DataTable getAgencyData(int id){
var dataTable = new DataTable();
// perform data access and fill up a data table
return dataTable;
}
}
}

Using DataContext in every function

I have a class that handles all database operations. I've read that it's better to use multiple DataContext instances for different read/write/update/delete operations as opposed to one DataContext instance that lives a long time.
That means every function that does read/write/update/delete on the DB needs to do this:
public int GetSomeID(string name)
{
using (XXDataContext context = new XXDataContext(connStr))
{
...
}
}
public int GetAnotherID(string name)
{
using (XXDataContext context = new XXDataContext(connStr))
{
...
}
}
public void WriteSomething(string text)
{
using (XXDataContext context = new XXDataContext(connStr))
{
...
}
}
opposed to having this using() only in constructor and having the context as a private member variable available to every function call.
With keeping the functionality of creating a new DataContext with every function call, is it possible to move this using() somewhere else so not every single function has to have this line in it?
You can use a method like this to avoid re-writing the using code:
private static void WithContext(Action<XXDataContext> action)
{
using(XXDataContext context = new XXDataContext(connStr))
action(context);
}
private static T WithContext<T>(Func<XXDataContext, T> function)
{
using(XXDataContext context = new XXDataContext(connStr))
return function(context);
}
This allows you to write:
public int GetSomeID(string name)
{
WithContext(context =>
{
//TODO use context
});
}
If that helps you.
Sorry for not answering your question directly:
You have read right thing. Context implements Unit Of Work pattern and supposed to be used like that.
However there can be a valid case when you need to do several operations within the same context and it would've been nice to right code like that:
using(var dal = new MyDalUOW()) {
dal.Delete(s1);
dal.Update(s2);
dal.Get(s3);
dal.Commit()
}
In order to have this you will create your Dal class which will implement IDisposable and will have method Commit
public class BaseDal: IDisposable {
private MyDbContext _context;
public BaseDal() { _context = new MyDbContext; }
public void Commit() { _context.SaveChanges(); }
}
And all your methods will use _context to perform operation.
So you will still have all those usings but in code using your DAL, not in the DAL itself.
If you use it in desktop/windows application it is no problem to have single DataContext, but you have to handle it wisely (according to the db technology, eg. EF or linq2sql) against synchronizing the datacontext cache data with database. And the one thing more, you have to use separate datacontext per thread.
I you use it in WEB app (ASP NET) then it is recommended and it is good practise to create a new instance of the datacontext per request (and dispose it on finish the request).
So it depends on your solution.
Alright, consider this code:
using (var fileStream = new FileStream(#"C:\temp\test.txt", FileMode.Open))
{
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
var text = Encoding.Default.GetString(bytes);
Console.WriteLine(text);
}
It leverages a class that uses IDisposable; just like the DataContext. Now, let's say we'd like to get rid of that using; we can do this:
Read(fileStream =>
{
var bytes = new byte[fileStream.Length];
fileStream.Read(bytes, 0, (int)fileStream.Length);
var text = Encoding.Default.GetString(bytes);
Console.WriteLine(text);
}, #"C:\temp\test2.txt");
static void Read(Action<FileStream> action, string path)
{
using (var fileStream = new FileStream(path, FileMode.Open))
{
action(fileStream);
}
}
Here you are injecting the code you want to execute while ensuring that the using statement is removed from the method. Further, you can guarantee that the using statement is going to be used. The output of this program is as expected:
Hello, World!
Hello, World; from an injected function!
Press any key to continue . . .

Dependent objects with RegisterInstance

I am using Unity block for Ioc implementation. I am using registerInstance and thats the way it will be. can't change it. The problem is if we do it what about the dependent objects? How to handle that. lets say
public ClientUser(IDataServiceManager dsm)
{
oDataServiceManager = dsm;
}
that works with registerType but as we have to creat the instance first
IClientUser clientUser = new ClientUser();
SnapFlowUnityContainer.Instance.RegisterInstance<IClientUser>(clientUser);
How can this work? our consultant said, use private getters to set the dependencies, let the class handle its dependent object? couldn't understand how to do that?
Update:
I need to know where i am wrong, How it will create the object of Dataservicemanger when i create clientUser
BootStrapper
IDataServiceManager dsm = new DataServiceManager();
IClientUser clientUser = new ClientUser();
SnapFlowUnityContainer.Instance.RegisterInstance<IDataServiceManager>(dsm);
SnapFlowUnityContainer.Instance.RegisterInstance<IClientUser>(clientUser);
Unit Test:
BootStrapper.Register();
IClientUser oIclientUser = SnapFlowUnityContainer.Instance.Resolve<IClientUser>();
ClientUser Class:
public class ClientUser : UserServiceBase, IClientUser
{
[Dependency]
private IDataServiceManager DataServiceMgr { get; set; }
}
If I understand you correctly this should work
SnapFlowUnityContainer.Instance.RegisterType<IDataServiceManager, DataServiceManager>();
var clientUser = SnapFlowUnityContainer.Instance.Resolve<ClientUser>();
SnapFlowUnityContainer.Instance.RegisterInstance<IClientUser>(clientUser);
ClientUser will get the DataServiceManager upon Resolve
If you want to enable Property injection in Unity, you can put a [Dependency] attribute on the property where you want to enable it. Something like this :
[Dependency]
public IClientUser ClientUser
{
get { return _clientUser; }
set
{
if (value == null) throw new ArgumentNullException("value",
String.Format(Thread.CurrentThread.CurrentUICulture,
Properties.Resource.ERR_ARGUMENT_NULL_USERSERVICE));
_clientUser = value;
}
}
Then, if you use RegisterInstance(clientUser) like in your example, this should work.
Another thing is when you need to to wire up objects not created by the container. Then you should use the method BuildUp
Hope this helps,
Thomas
public class ClientUser : UserServiceBase, IClientUser
{
IDataServiceManager _dataServiceManager;
public ClientUser()
{
}
private IDataServiceManager DataServiceMgr
{
get {
_dataServiceManager = SnapFlowUnityContainer.Instance.Resolve<IClientUser>();
return _dataServiceManager;
}
}
}
You do not need the [Dependency] attribute on properties, it can be done either via a configuration file or the fluent registration API. There's 2 ways of achieving this with the fluent API, for your scenario you will probably use the first method:
Method 1:
SnapFlowUnityContainer.Instance
.Configure<InjectedMembers>()
.ConfigureInjectionFor<IClientUser>(
new InjectionProperty("DataServiceMgr"));
Method 2:
SnapFlowUnityContainer.Instance
.RegisterType<IClientUser, ClientUser>(
new ExternallyControlledLifetimeManager(),
new InjectionProperty("DataServiceMgr"))
.BuildUp<IClientUser>(clientUser);
Be careful of using "SnapFlowUnityContainer.Instance" to register and resolve (service location pattern) types, preferably you need to make sure that registration only occurs once during the application lifetime.

Entity Framework Best Practices In Business Logic?

I am using the Entity framework for the first time, and would like to know if I am using in the best practice.
I have created a separate class in my business logic which will handle the entity context. the problem I have, is in all the videos I have seen they usually wrap the context in a using statement to make sure its closed, but obviously I can't do this in my business logic as the context will be closed before I can actually use it?
So is this ok what I'm doing? A couple of examples:
public IEnumerable<Article> GetLatestArticles(bool Authorised)
{
var ctx = new ArticleNetEntities();
return ctx.Articles.Where(x => x.IsApproved == Authorised).OrderBy(x => x.ArticleDate);
}
public IEnumerable<Article> GetArticlesByMember(int MemberId, bool Authorised)
{
var ctx = new ArticleNetEntities();
return ctx.Articles.Where(x => x.MemberID == MemberId && x.IsApproved == Authorised).OrderBy(x => x.ArticleDate);
}
I just want to make sure I'm not building something that's going to die when a lot of people use it?
It really depends on how to want to expose your repository/data store.
Not sure what you mean by "the context will be closed, therefore i cannot do business logic". Do your business logic inside the using statement. Or if your business logic is in a different class, then let's continue. :)
Some people return concrete collections from their Repository, in which case you can wrap the context in the using statement:
public class ArticleRepository
{
public List<Article> GetArticles()
{
List<Article> articles = null;
using (var db = new ArticleNetEntities())
{
articles = db.Articles.Where(something).Take(some).ToList();
}
}
}
Advantage of that is satisfying the good practice with connections - open as late as you can, and close as early as you can.
You can encapsulate all your business logic inside the using statement.
The disadvantages - your Repository becomes aware of business-logic, which i personally do not like, and you end up with a different method for each particular scenario.
The second option - new up a context as part of the Repository, and make it implement IDisposable.
public class ArticleRepository : IDisposable
{
ArticleNetEntities db;
public ArticleRepository()
{
db = new ArticleNetEntities();
}
public List<Article> GetArticles()
{
List<Article> articles = null;
db.Articles.Where(something).Take(some).ToList();
}
public void Dispose()
{
db.Dispose();
}
}
And then:
using (var repository = new ArticleRepository())
{
var articles = repository.GetArticles();
}
Or the third-option (my favourite), use dependency injection. Decouple all the context-work from your Repository, and let the DI container handle disposal of resources:
public class ArticleRepository
{
private IObjectContext _ctx;
public ArticleRepository(IObjectContext ctx)
{
_ctx = ctx;
}
public IQueryable<Article> Find()
{
return _ctx.Articles;
}
}
Your chosen DI container will inject the concrete ObjectContext into the instantiation of the Repository, with a configured lifetime (Singleton, HttpContext, ThreadLocal, etc), and dispose of it based on that configuration.
I have it setup so each HTTP Request gets given a new Context. When the Request is finished, my DI container will automatically dispose of the context.
I also use the Unit of Work pattern here to allow multiple Repositories to work with one Object Context.
You may have also noticed I prefer to return IQueryable from my Repository (as opposed to a concrete List). Much more powerful (yet risky, if you don't understand the implications). My service layer performs the business logic on the IQueryable and then returns the concrete collection to the UI.
That is my far the most powerful option, as it allows a simple as heck Repository, the Unit Of Work manages the context, the Service Layer manages the Business Logic, and the DI container handles the lifetime/disposal of resources/objects.
Let me know if you want more info on that - as there is quite a lot to it, even more than this surprisingly long answer. :)
I would have the ctx as a private variable within each class, then create a new instance of this each time and then dispose when finished.
public class ArticleService
{
private ArticleEntities _ctx;
public ArticleService()
{
_ctx = new ArticleEntities();
}
public IEnumerable<Article> GetLatestArticles(bool Authorised)
{
return _ctx.Articles.Where(x => x.IsApproved == Authorised).OrderBy(x => x.ArticleDate);
}
public IEnumerable<Article> GetArticlesByMember(int MemberId, bool Authorised)
{
return _ctx.Articles.Where(x => x.MemberID == MemberId && x.IsApproved == Authorised).OrderBy(x => x.ArticleDate);
}
public void Dispose()
{
_ctx.Dispose();
_ctx = null;
}
}
Then when calling this.
ArticleService articleService = new ArticleService();
IEnumerable<Article> article = articleService.GetLatestArticles(true);
articleService.Dispose(); // killing the connection
This way you can also add/update other objects within the same context and call a save method which saves any changes to the db through the Entity.
In my experience this code is not good, because you lose the capacity to navigate relationships through navigation properties.
public List<Articles> getArticles( ){
using (var db = new ArticleNetEntities())
{
articles = db.Articles.Where(something).ToList();
}
}
Using this approach you can't use the following code because a.Members is always null( db context is close and cant get data automatically).
var articles = Data.getArticles();
foreach( var a in articles ) {
if( a.Members.any(p=>p.Name=="miki") ) {
...
}
else {
...
}
}
}
Using only a global db context is a bad idea because you must use a delete changes function
in a point of your application yo do this but don't save changes and close the window
var article= globalcontext.getArticleByID(10);
article.Approved=true;
then in another point of application you make some operation and save
//..... something
globalcontext.saveChanges();
in this case previous article approved property is set to modified by entity framework. When you save, approved is set true!!!
Best approach for me is use 1 context per class
You can pass context to another external method if you need
class EditArticle {
private DbEntities de;
private currentAricle;
public EditArticle() {
de = new DbEntities; //inizialize on new istance
}
loadArticleToEdit(Articele a){
// a is from another context
currentArticle= de.Article.Single(p=>p.IdArticle==a.IdArticle){
}
private saveChanges(){
...
pe.saveChanges();
}
}
What you can also do is store your context at a higher level.
E.g., you can have a static class storing the current context:
class ContextManager
{
[ThreadStatic]
public static ArticleEntities CurrentContext;
}
Then, somewhere outside you do something like this:
using (ContextManager.CurrentContext = new ArticleEntities())
{
IEnumerable<Article> article = articleService.GetLatestArticles(true);
}
Then, inside the GetLastestArticles, you just use the same ContextManager.CurrentContext.
Of course, this is just the basic idea. You can make this a lot more workable by using service providers, IoC and such.
You can start preparing Entity Framework from data access layer by creating a generic repository class for all required Entity Framework functions. Then you can used it in Business layer (Encapsulated)
Here are the best practices that I have used for Entity Framework in data, business, and UI layers
Techniques used for this practice:
Applying SOLID architecture principles
Using Repository design pattern
Only one class to go (and you will find it ready)

Categories