If you have a class library that uses classes from another DLL, for instance EntityFramework.Dll
, then in your end product your DLL needs to be able to find this other DLL.
The most easy way to take care of this is to add this other DLL to your references. This will automatically take care that after proper deployment (installation) the other DLL is also copied.
However, quite often you don't want that the users of your DLL also have to refer to the other DLL. Luckily this is not needed as long as you take care that none of the identifiers of the other DLL is in one of your public classes / interfaces
So if your class needs EntityFramework.DLL, and you don't want that users of your class don't have to refer to EntityFramework.DLL, make sure that nothing of the Entity Framework identifiers is public.
The best method is to use interfaces. You could also try to make the items that use Entity Framework internal in your class.
So instead of:
public class DbSchool : DbContext
{
...
}
do the following:
public interface IDbSchool
{
IQueryable<Student> Students {get;}
IQueryable<Teacher> Teachers {get;}
IQueryable<ClassRoom> ClassRooms {get;}
IQueryable<Course> Courses {get;}
}
internal class DbSchool : DbContext, IDbSchool
{
internal DbSet<Student> Students {get; set;}
internal DbSet<Teachter> Teachers {get; set;}
...
// Explicit interface implementation of IDbSchool:
IQueryable<Student> IDbSchool.Students {get => this.Students;}
IQueryable<Teacher> IDbSchool.Teachers {get => this.Teachers;}
...
}
As long as you write code inside your DLL you can use everything from Entity Framework, after all, your DLL refers to it.
The users of your DLL don't refer to Entity Framework, so they can't use identifiers like DbContext
and DbSet
. However, if they refer to your DLL they can use identifiers as Student
, Teacher
, Course
and of course IDbSchool
.
But how does my user create an object of class DbSchool?
Answer: He can't. So you have to create a factory function that returns an IDbSchool:
public static class SchoolFactory
{
public static IDbSchool CreateSchoolContext(...)
{
return new DbSchool(...);
}
}
Usage:
using (IDbSchool dbSchool = SchoolFactory.CreateSchoolContext(...))
{
var teachersWithStudents = dbSchoolTeachers
.Select(teacher => new
{
Id = teacher.Id,
Name = teacher.Name,
Students = teacher.Students.Select(student => new
{
Id = student.Id,
Name = student.Name,
})
.ToList(),
})
.Where(teacher => teacher.Students.Any());
}
Note: because you want to properly Dispose your DbSchool
, your IDbSchool
should be derived from IDisposable
public interface IDbSchool, IDisposable {...}