accessibility between projects question
I have 2 library projects: AProject and BProject and one web project: WebProject.
AProject has a class:public class WorkerManager {
public Worker Get(long workerId) {
....
....
}
public Worker Get(Guid companyId, long workerId) {
....
....
}
}
I would like classes from BProject to be able to use the first vers开发者_开发知识库ion of the Worker Get:
WorkerManager a=new WorkerManager ();
a.Get(8);
And I would like this method to be hidden for the web project.
If I make the Worker Get(long workerId)
internal, then BProject will not be able to use this method, and if I make it public the web project gets access to this method.
How can I prevent access to the web project and allow access to the BProject?
It sounds like you need Friend Assemblies.
They basically allow you to make your class internal, but specify that BProject
should have access to the internal classes of AProject
.
Update
I've never actually had to use Friend Assemblies, so I won't be able to give you any better direction than Google can.
Other people have mentioned using interfaces, and I agree that this is generally a good approach. Whether or not it works for you will depend on the structure of your code, though. Let's say you move the WorkerManager
class to a new Project (C). Project C depends on Project B. Project A depends on both C and B. WebProject depends on A and B.
/-------------\
WebProject -> A -> C -> B
\-------/
Project B now defines an interface like the following:
public interface IWorkerManager
{
public Worker Get(long workerId);
}
And WorkerManager in Project C implements the interface:
public class WorkerManager : IWorkerManager {...}
Now Project A can produce IWorkerManager
s via a factory, so your Web Project never has to say new WorkerManager()
.
public class WorkerManagerFactory
{
public IWorkerManager Get() {return new WorkerManager();}
}
Now it's still possible for Project A to access the other methods:
new WorkerManager().Get(compGuid, workerId);
... but Web Project can only access what's been defined by the interface:
new WorkerManagerFactory().Get().Get(workerId);
This illustrates one way that you might achieve what you're looking for. You could find better solutions by leveraging Dependency Injection, but this explanation is getting well beyond the scope of the original question.
You could use InternalsVisibleTo
attribute and make the method internal
.
But I'm not sure it's a good design, hiding methods this way. If it's just an implementation detail, it should be private. If it's part of public surface of the class, it should be public to everyone. There's not much space in between that (ignoring derived classes and protected members).
One situation where this can be useful is unit-testing private functionality. There are probably other uses, but they should be pretty rare.
精彩评论