I'm currently using StructureMap to inject an NHibernateRegistry instance into my DAL, which configures NHibernate for a single connection string and bootstraps a Singleton FluentConfiguration for my single-user app.
How should I modify my Fluent NHibernate configuration to use a different database based on a {tenant} routing parameter in my routing URL?
Routing example:
{tenant}/{controller}/{action}/{id}
...where requests for branch1/Home/Index and branch2/Home/Index use the same application code, but different databases to retrieve the data displayed.
I solved this problem in the past for StructureMap and LINQ by injecting a per-request TenantContext object, which retrieved the routing parameter from the HttpContext it accepted as a constructor parameter and specified a different LINQ data context.
However, I suspect NHibernate has a better of handling this than I could cook up.
Partial NHibernateRegistry class
public class NHibernateRegistry : Registry
{
// ... private vars here
public NHibernateRegistry()
{
var cfg = Fluently.Configure()
.Database(MsSqlConfiguration
.MsSql2008.ConnectionString(c =>
c.FromConnectionStringWithKey("TenantConnectionStringKey")))
// where to inject this key?
.ExposeConfiguration(BuildSchema)
.Mappings(x =>
x.FluentMappings.AddFromAssembly(typeof(UserMap).Assembly)
For<FluentConfiguration>().Singleton().Use(cfg);
var sessionFactory = cfg.BuildSessionFactory();
For<ISessionFactory>().Singleton()
.Use(sessionFactory);
For<ISession>().HybridHttpOrThreadLocalScoped()
.Use(x => x.GetInstance<ISessionFactory>().OpenSession());
For<IUnitOfWork>().HybridHttpOrThreadLocalScoped()
.Use<UnitOfWork>();
For<IDatabaseBuilder>().Use<DatabaseBuilder>();
}
}
StructureMap configuration:
public static class Bootstrapper
{
public static void ConfigureStructureMap()
{
ObjectFactory.Initialize(Init);
}
private static void Init(IInitializationExpression x)
{
x.AddRegistry(new NHibernateRegistry()); // from Data project
}
}
I'm new to NHibernate, so I am unsure of scoping my sessions and configurations. Does NHibernate have a built-in way to handle this?
This worked for me in an a module
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(x => x.FromConnectionStringWithKey("IMB"))
.Cache(c => c.UseQueryCache().QueryCacheFactory<StandardQueryCacheFactory>()
.RegionPrefix("IMB")
.ProviderClass<HashtableCacheProvider>()
.UseMinimalPuts()).UseReflectionOptimizer())
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("IMB.Data")))
.Mappings(m => m.FluentMappings.AddFromAssembly(Assembly.Load("IMB.Security")))
.ExposeConfiguration(
c => c.SetProperty("current_session_context_class", "web"))
.ExposeConfiguration(cfg => _configuration = cfg)
.BuildSessionFactory();
The problem is that you really want your ISessionFactory object to be a singleton. This means its best not to specify the connection string when creating the ISessionFactory. Have your tried creating the ISessionFactory without specifying a connection string and then passing a manually created connection to ISessionFactory.OpenSession?
For example:
public ISession CreateSession()
{
string tennantId = GetTennantId();
string connStr = ConnectionStringFromTennant(tennantId);
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
session = sessionFactory.OpenSession(conn);
}
And then tell StructureMap to call this method.
The downside is that you can't now from build the database schema when creating the ISessionFactory, but maybe creating database schemas in web applications isn't that great an idea anyway?
Related
I have a Symfony 3.4 app that could contain multiple companies.
Each company have their own config, and their own data in db, so I need that each company have their own db.
When any user login, The application has a "core database" containing user's info.
After user login the application must change configuration for connect to user company database, that had saved in "core database".
There are necessary steps:
One user enter his user and password
the app look into central db and get user's authentication.
The app get user configuration to change.
The app change the configuration and now, sql request will be to the company's db.
It is possible? If not, is there any alternative?
Thank you so much!
You have to work here with multiple entity managers and connections and and idea is to use a subscriber that retrieves the current customer based on the user. This subscriber (or another service) will set a global variable containing the name of the entity manager.
// A subscriber (high level priority) or a service already set $customerName
// In your controller or in a service
$customerEntityManager = $this->getDoctrine()->getManager($customerName);
Check also this bundle for ideas https://github.com/vmeretail/multi-tenancy-bundle
Edit
Use and adapt to your needs this file https://github.com/vmeretail/multi-tenancy-bundle/blob/master/Service/TenantResolver.php
Here you just need to resolve tenant from the current User.
In your controller:
...
public function index(TenantResolver $tenantResolver)
{
$customerEntityManager = $this->getDoctrine()->getManager($tenantResolver->getTenant()->getName()); // or getId() or something else
}
In a service:
...
use Doctrine\Common\Persistence\ManagerRegistry;
private $tenantResolver;
private $managerRegistry;
public function__construct(TenantResolver $tenantResolver, ManagerRegistry $managerRegistry)
{
$this->tenantResolver = $tenantResolver;
$this->managerRegistry = $managerRegistry;
}
public function doSomething()
{
$this->managerRegistry->getManager($this->tenantResolver->getTenant()->getName()); // or getId() or something else
}
It's the idea, there must be something better to do here like injecting directly the right manager in the service/controller constructor.
I found the following solution for Symfony 4 and i think it should work for symfony 3.4 as well.
I created a service that copies the default entity manager in a new one connecting to another database:
namespace App\Service;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Doctrine\ORM\EntityManagerInterface;
class CustomEntityManagerHelper
{
private $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
/*
* get entity manager for another database
*/
public function getManagerForDatabase($db_name): EntityManagerInterface
{
$conn = array(
'driver' => 'pdo_mysql',
'user' => 'root',
'password' => 'mypass',
'dbname' => $db_name
);
return \Doctrine\ORM\EntityManager::create(
$conn,
$this->em->getConfiguration(),
$this->em->getEventManager()
);
}
}
Until now it was very easy but the Repository class still uses the default entitymanager. So i added a method setEntityManager to the Repositories:
<?php
namespace App\Repository;
use App\Entity\Product;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ORM\EntityManagerInterface;
class ProductRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Product::class);
}
public function setEntityManager(EntityManagerInterface $entityManager): self
{
$this->_em = $entityManager;
return $this;
}
// custom methods here
}
Now i can use the custom entity manager AND set that to the repository:
use App\Service\CustomEntityManagerHelper;
// ...
/**
* #Route("/products", name="app_product", methods={"GET"})
*/
public function index(CustomEntityManagerHelper $helper): Response
{
$myManager = $helper->getManagerForDatabase($this->getUser()->getDatabaseName());
$products = $myManager->getRepository('App:Product')
->setEntityManager($myManager) // IMPORTANT!
->findAll();
return $this->render('product/index.html.twig', [
'products' => $products
]);
}
I open one database at the start, then need to open another database based on user selecting two values. The database selection has to be at run-time and will change every time.
Have tried to access the Connection String using the Connection String class and have tried other options like Singleton which I do not understand. I am running this on a local Windows 10 system running SQL Server Express. Am coding using Asp.Net Core 2.1
> ASP.Net Core v2.1
Building multi tenant, multi year application
Every client will have one SQL DATABASE per year
I hope to have a table with the following structure
COMPANY_CODE VARCHAR(3),
COMPANY_YEAR INT,
COMPANY_DBNAME VARCHAR(5)
Sample Data
COMPANY_CODE: AAD
COMPANY_YEAR: 19
COMPANY_DB: AAD19
COMPANY_CODE: AAD
COMPANY_YEAR: 18
COMPANY_DB: AAD18
COMPANY_CODE: AAD
COMPANY_YEAR: 17
COMPANY_DB: AAD17
So, every company will multiple rows - one for each financial year.
The COMPANY_DB column will store the DB name to open for that session.
Once the user is authenticated, I want to change the connection string to point to the database in the COMPANY_DB column of the selected row and then let the logged in user perform transactions.
I am unable to figure out how to change the connection string that is embedded in startup.cs.
Any tips on how to achieve this will be most appreciated.
I figured out that you are using one DbContext class for each database. See here for more information: docs.
Remove AddDbContext from Startup, remove OnConfiguring from DbContext and pass options to the constructor.
public class BloggingContext : DbContext
{
public BloggingContext(DbContextOptions<BloggingContext> options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
}
Then, write service providing DbContext:
public interface IBlogContextProvider
{
BlogContext GetBlogContext(string connectionString);
}
public class BlogContextProvider : IBlogContextProvider
{
BlogContext GetBlogContext(string connectionString)
{
var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlServer(connectionString);
return new BlogContext(optionsBuilder);
}
}
Add service in your Startup.cs:
services.AddScoped<IBlogContextProvider, BlogContextProvider>();
Now you can use DI:
public class HomeController : Controller
{
private IBlogContextProvider _provider;
public HomeController(IBlogContextProvider provider)
{
_provider = provider;
}
public ActionResult Index()
{
using (var context = _provider.GetBlogContext(<your connection string>))
{
//your code here
}
return View();
}
}
EDIT: Of course, you can write ContextProvider as generic.
In my task (dotnet core, c#), it is necessary to select one of the databases and make some kind of manipulation in accordance with the query.
According with microsoft docs, it's look like:
public class db1 : DbContext, Idb
{
public db1(DbContextOptions options) : base(options)
{}
}
public class db2 : DbContext, Idb
{
public db2(DbContextOptions options) : base(options)
{}
}
In Startup.cs
services.AddDbContext<db1>(options =>
options.UseSqlServer(Configuration.GetConnectionString("db1")));
services.AddDbContext<db2>(options =>
options.UseSqlServer(Configuration.GetConnectionString("db2")));
This allows you to register in DI and access a specific database connection instance, but all databases are hardcoded. This is a poor code. How is it better to make registration in DI by id of a database and select from DI's service by this id in a controller?
It is not so bad because you can change the connection string according to your environment, having different versions of your appsetings.json (appsettings.dev.json, appsettings.release.json and so on and so forth)
On the other hand you coulduse these context in your controllers contructors, i.e
ctor 1:
public FirstController(db1 context)
ctor2:
public SecondController(db2 context)
maybe, alse, ctor3:
public ThirdController(db1 contextA, db2 contextB )
BUT:
a) consider naming conventions (Idb?? db1??)
b) Why would you like to have Two same-kind-of repositories ... Oh! Are you trying to have a Generic repository pattern?? Then your answer is here: https://github.com/Arch/UnitOfWork (Im using it and I'm very hapy with the result and the performance, I'll paste an example bellow)
Using IUnitOfWork:
In your controller:
public YourController(IUnitOfWork unitOfWork)
{
try
{
_unitOfWork = unitOfWork;
// seeding
var ItemRepository = _unitOfWork.GetRepository<Item>();
//ETC...
In your StartUp, in ConfigureServices, call this method:
private void AddEntityFrameworkAndDbContext(IServiceCollection services)
{
services.AddEntityFrameworkSqlServer();
var migrationsAssemblyName = typeof(YourContext).GetTypeInfo().Assembly.GetName().Name;
services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(Your.ConnectionString.NoMAtterHowYouGetIt,
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.MigrationsAssembly(migrationsAssemblyName);
sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null);
}); // Man, this is for free, I spent days getting it to work
},
ServiceLifetime.Scoped // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request)
).AddUnitOfWork<YourContext>();
}
And in Configure try something like:
app.EnsurePopulated(app.ApplicationServices.GetRequiredService());
I hope it helps you,
Juan
I am making a project using JSF, and I know how to get data from my view. I also know how to get data with the JDBC connector. And also how to put data in the view, from some objects, but my question is:
How to put data directly from my database, for example a list of person, in JSF, for example with the tag <h:outputText value="#{}"/> ?
I have found some examples with instantiate objects, but I did not found a real example with data from a DB.
JSF is just an MVC framework to develop web applications in Java. JSF doesn't associate with any data source at all. The only data JSF will use is retrieved from:
The data already stored in the proper object as attribute: HttpServletRequest, HttpSession or ServletContext.
The request/view/session/application context in form of fields in the managed beans, recognized by classes decorated as #ManagedBeans or #Named if using CDI. The data of these fields will be stored as attributes in the objects mentioned in the section above, depending on the scope of the managed bean.
By knowing this, then the only thing you should worry about is to fill the fields in your managed beans. You can fill them with incoming data from database, from a web service or whatever data source you have in mind.
For example, if you want/need to populate your data to pre process a request, you can do the following:
#ManagedBean
#ViewScoped
public class SomeBean {
List<Entity> entityList;
#PostConstruct
public void init() {
SomeService someService = new SomeService();
entityList = someService.findEntityList();
}
//getters and setters for the list...
}
//as you can see, this class is just pure Java
//you may use other frameworks if you want/need
public class SomeService {
public List<Entity> findEntityList() {
String sql = "SELECT field1, field2... FROM table";
List<Entity> entityList = new ArrayList<>();
try (Connection con = ...; //retrieve your connection somehow
PreparedStatement pstmt = con.prepareStatement(sql)) {
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Entity entity = new Entity();
entity.setField1(rs.getString("field1"));
entity.setField2(rs.getString("field2"));
//...
entityList.add(entity);
}
} catch (Exception e) {
//handle exception ...
e.printStackTrace();
}
return entityList;
}
}
I am using Enterprise Library 5.0 in my win-form Application.
1. Regarding creating instances of Enterprise Library objects
What is the best way to Resolve the reference for Logging / exception objects? In our application, we have different applications in solution. So Solutions have below project:
CommonLib (Class Lib)
CustomerApp (winform app)
CustWinService (win service proj)
ClassLib2 (class Lib)
I have implemented logging / exceptions as below in CommonLib project. Created a class AppLog as below:
public class AppLog
{
public static LogWriter defaultWriter = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
public static ExceptionManager exManager = EnterpriseLibraryContainer.Current.GetInstance<ExceptionManager>();
public AppLog()
{
}
public static void WriteLog(string LogMessage, string LogCategories)
{
// Create a LogEntry and populate the individual properties.
if (defaultWriter.IsLoggingEnabled())
{
string[] Logcat = LogCategories.Split(",".ToCharArray());
LogEntry entry2 = new LogEntry();
entry2.Categories = Logcat;
entry2.EventId = 9007;
entry2.Message = LogMessage;
entry2.Priority = 9;
entry2.Title = "Logging Block Examples";
defaultWriter.Write(entry2);
}
}
}
And then I used Applog class as below for logging and exception in different projects:
try
{
AppLog.WriteLog("This is Production Log Entry.", "ExceCategory");
string strtest = string.Empty;
strtest = strtest.Substring(1);
}
catch (Exception ex)
{
bool rethrow = AppLog.exManager.HandleException(ex, "ExcePolicy");
}
So its the correct way to use Logging and Exception? or any other way i can improve it?
2. Logging File Name dynamic
In logging block, we have fileName which need to be set in app.config file. Is there a way I can assign fileName value dynamically through coding? Since I don't want to hard code it in config file and paths are different for production and development environment.
Thanks
TShah
To keep your application loosely coupled and easier to test, I would recommend defining separate logging and exception handling interfaces, then having your AppLog class implement both. Your application can then perform logging and exception handling via those interfaces, with AppLog providing the implementation.
You can have a different file name set per environment using config transforms, which I believe you can use in a winforms application by using Slow Cheetah.